Array Initialization

Started by
16 comments, last by RomanR 22 years, 4 months ago
I have a bit of a problem initializing a 2d array with color data from an image.
Here is what I have: UINT w,h which are initialized with width and height of the image like so:

w = img->GetWidth();
h = img->GetHeight();
 
Now initializing an array like so:

D3DCOLOR c[w][h];
 
does not compile.
C:\Projects\Engine\Engine.cpp(42) : error C2057: expected constant expression
C:\Projects\Engine\Engine.cpp(42) : error C2466: cannot allocate an array of constant size 0
I know that w and h get initialised to the right width and height. Please assist!
Romanroman_rodov@hotmail.com
Advertisement
Its not possible to statically declare an array using variable sizes. IF your code looked like

D3DCOLOR c[10][10];

...that would work.

What you need in your case is dynamic allocation.

D3DCOLOR *c = new D3DCOLOR[w*h]; should work fine

Oh and remember to do a

delete [] c;

when you dont need the array anymore.

Hope that helps

-MrZ
Ok, wouldn''t this declare a 1d array? I tried this with just 1 index like so: *c = pixelColor; I get "illegal indirection" error. *c[j] does not let me compile either. Please explain your way in a bit more depth please? </i>
Romanroman_rodov@hotmail.com
in the last post it was supposed to be *c"["i"]" = pixelColor;
I can''t figure out these mark up tags in the forum. Sorry.
Romanroman_rodov@hotmail.com
you can''t declare the array inline with variables the way you are trying, only with constants. To work with variables, you need to create the array dynamically:

D3DCOLOR *c = new D3DCOLOR[w];
for (int i=0; i<w; i++)
c = new D3DCOLOR[h];

and when you are done, you need to delete the memory in the same way:

for (int j=0; j<w; j++)
delete c[j];
delete [] c;
<quote>
D3DCOLOR *c = new D3DCOLOR[w];
for (int i=0; i<w; i++)
c = new D3DCOLOR[h];
</quote>

of course that should''ve read:

D3DCOLOR *c = new D3DCOLOR[w];
for (int i=0; i<w; i++)
c<b></b> = new D3DCOLOR[h];

This board really does need a preview button for posters...
let''s try that again... it should''ve read

D3DCOLOR *c = new D3DCOLOR[w];
for (int i=0; i<w; i++)
c = new D3DCOLOR[h];

notice that i''m assigning a new value to c, not overwriting c.<br><br>I reiterate on the preview button… i''m gonna go register now, so i can edit my next post <img src="wink.gif" width=15 height=15 align=middle> </i>
D3DCOLOR *c = new D3DCOLOR[w];
for (int i=0; i<w; i++)
c = new D3DCOLOR[h];


if this doesn''t work, I give up...
i figured out the problem, it''s because it interprets blocks for html, and its turning my index into an italisize(sp) tag. With modified for flags, it looks like this:

D3DCOLOR *c = new D3DCOLOR[w];
for (int x=0; x<w; x++)
{
c[x] = new D3DCOLOR[h];
}


for (int y=0; y<w; y++)
{
delete c[y];
}
delete [] c;
Rule #1: Do not use "i" as a variable name.

This topic is closed to new replies.

Advertisement