0

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 ?

4

5 に答える 5

3

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*.

于 2012-06-01T17:46:30.200 に答える
1

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.

于 2012-06-01T17:48:41.757 に答える
1

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.

于 2012-06-01T17:51:47.490 に答える
1

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]
于 2012-06-01T18:00:55.310 に答える
1

Yes, it's quite incorrect to use new[]. What you're looking for is std::vector<unsigned int> var(800 * 600);.

于 2012-06-01T18:07:53.070 に答える