c0d3rz
c0d3rz

Reputation: 679

C++ Initialization query

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 ?

Upvotes: 0

Views: 158

Answers (5)

Puppy
Puppy

Reputation: 146910

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

Upvotes: 1

betabandido
betabandido

Reputation: 19704

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.

Upvotes: 1

Eric Finn
Eric Finn

Reputation: 8995

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]

Upvotes: 1

evanmcdonnal
evanmcdonnal

Reputation: 48076

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.

Upvotes: 1

Edward Loper
Edward Loper

Reputation: 15944

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

Upvotes: 3

Related Questions