I'm having problems creating an array with a dynamic size using new.

Here is the relevant code:

enum LandCondition
{
	Bad,
	Good
};

//...

int IMG_WIDTH, IMG_HEIGHT;
LandCondition* land;

//...

land = new LandCondition[IMG_WIDTH][IMG_HEIGHT];//causes errors

The errors VC++ gives me are:
error C2540: non-constant expression as array bound
error C2440: '=' : cannot convert from 'LandCondition (*)[1]' to 'LandCondition *'

What's causing this? I've done things similar to this before without issues.

Recommended Answers

All 5 Replies

land = new LandCondition[IMG_WIDTH];
for(int i = 0; i < IMG_WIDTH; ++i)
  land[i] = new LandContion[IMG_HEIGHT];

Thanks, though I'm still having some problems. Does land now need to be a double pointer? I finally got the code to compile, but then I ran into a write error.

LandCondition** land;

//...

*land = new LandCondition[IMG_WIDTH];//runtime error

//...

for(int i = 0;i < IMG_WIDTH;i++)
	land[i] = new LandCondition[IMG_HEIGHT];

It's complaining that it can't write to location 0x0000000, which makes sense I guess, but I don't know how to resolve this.

Thanks, though I'm still having some problems. Does land now need to be a double pointer? I finally got the code to compile, but then I ran into a write error.

LandCondition** land;

//...

*land = new LandCondition[IMG_WIDTH];//runtime error

//...

for(int i = 0;i < IMG_WIDTH;i++)
	land[i] = new LandCondition[IMG_HEIGHT];

It's complaining that it can't write to location 0x0000000, which makes sense I guess, but I don't know how to resolve this.

land is to be a 2-dimensional dynamic array of dimensions IMG_WIDTH x IMG_HEIGHT? If so, try something like this:

LandCondition** land;
land = new LandCondition*[IMG_WIDTH];
for (int i = 0; i < IMG_WIDTH; i++)
{
    land[i] = new LandCondition[IMG_HEIGHT];
}
commented: helpful +1

Yes, land should be:

LandCondition** land;

Then the code I posted, with the correction by VernonDozier.

Thanks. That did it. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.