PDA

View Full Version : Problem with new and pointer array?


Mars_999
2002.07.25, 01:35 AM
Not sure why this code dont' work?



struct FOO
{
int a;
};

const int arraysize = 10;

int main(int argc, char *argv[])
{
FOO *foo[arraysize][arraysize] = new FOO; //why don't this work?
FOO *foo[arraysize][arraysize] = new FOO[arraysize][arraysize]; // this dont' work either?

int *x = new int; // this is the correct syntax

return 0;
}


I think the reason why the first dont' work is the compiler dosen't know how much RAM to allocate? The second would seem logical to solve that but it don't work? I know the last one works, since that is the syntax for a pointer using new. =) Thanks

szymczyk
2002.07.25, 02:03 AM
Originally posted by Mars_999
Not sure why this code dont' work?



struct FOO
{
int a;
};

const int arraysize = 10;

int main(int argc, char *argv[])
{
FOO *foo[arraysize][arraysize] = new FOO; //why don't this work?
FOO *foo[arraysize][arraysize] = new FOO[arraysize][arraysize]; // this dont' work either?

int *x = new int; // this is the correct syntax

return 0;
}




The problem is that by declaring the following:

FOO *foo[arraysize][arraysize]

You have fixed the size of the array to be arraysize rows by arraysize columns. Trying to dynamically allocate an array whose size you have fixed will cause a problem. Assuming you want to dynamically allocate the array, you should declare the variable foo like the following:

FOO* foo;

The easiest way to allocate a 2D array in C++ is to declare a 1D array like the following:

foo = new FOO[rows * columns];

Then treat the array like it is 2D. For example:

arrayIndex = (row * number of colums) + column;