Is this 2D array initialization a bad idea?

Posted by Brendan Long on Stack Overflow See other posts from Stack Overflow or by Brendan Long
Published on 2010-05-16T03:16:17Z Indexed on 2010/05/16 3:20 UTC
Read the original article Hit count: 224

I have something I need a 2D array for, but for better cache performance, I'd rather have it actually be a normal array. Here's the idea I had but I don't know if it's a terrible idea:

const int XWIDTH = 10, YWIDTH = 10;
int main(){
    int * tempInts = new int[XWIDTH * YWIDTH];
    int ** ints = new int*[XWIDTH];
    for(int i=0; i<XWIDTH; i++){
        ints[i] = &tempInts[i*YWIDTH];
    }
    // do things with ints
    delete[] ints[0];
    delete[] ints;
    return 0;
}

So the idea is that instead of newing a bunch of arrays (and having them placed in different places in memory), I just point to an array I made all at once.

The reason for the delete[] (int*) ints; is because I'm actually doing this in a class and it would save [trivial amounts of] memory to not save the original pointer.

Just wondering if there's any reasons this is a horrible idea. Or if there's an easier/better way. The goal is to be able to access the array as ints[x][y] rather than ints[x*YWIDTH+y].

© Stack Overflow or respective owner

Related posts about memory-allocation

Related posts about c++