Can someone please tell me if there is anything incorrect with this initialization:
static unsigned char* var[1]
var[0] = new unsigned char[ 800 * 600 ]
Is this creating a 2D array at var[0] ? Is this even valid ?
Can someone please tell me if there is anything incorrect with this initialization:
static unsigned char* var[1]
var[0] = new unsigned char[ 800 * 600 ]
Is this creating a 2D array at var[0] ? Is this even valid ?
It's creating a single array with 480,000 elements (aka 800*600) and storing it in var[0]. It is not creating a 2D array. It's valid as long as var[0]
is an unsigned char*
.
Your code is not correct, since var[0]
is not a pointer anymore.
You may want to do something like:
static unsigned char* var;
var = new unsigned char[800 * 600];
That does not create a 2D array. It is just a 1D array. Having said that, you can use it as a 2D array if you compute the offset yourself. For instance to access position (row, col) you could do:
var[row * 600 + col]
If you really want a "true" 2D array, you will need to use for instance:
static unsigned char** var;
var = new unsigned char*[600];
for (int i = 0; i < 600; i++)
var[i] = new unsigned char[800];
Of course, if you do not need to dynamically specify the array size at runtime, you can just use a statically allocated array:
static unsigned char var[600][800];
BTW, I assume 600 is the number of rows and 800 the number of cols (like in a matrix). That is why I always use 600 in the first index. Otherwise, just swap the values.
I think you want something more like (although I may be interrupting the question wrong);
static unsigned char* var = new char*[800]
for (int i =0; i < 800; i++)
var[i] = new char[600]
That will give you a 800x600 2d character array.
It is creating a 1-d array of length (800*600) at var[0]. You'll be able to access its elements with:
var[0][0]
var[0][1]
...
var[0][800*600-1]
Yes, it's quite incorrect to use new[]
. What you're looking for is std::vector<unsigned int> var(800 * 600);
.