-1

I've [attempted] to implement a two dimensional array, for a zBuffer as follows:

struct Properties {
     ....
     double** zBuffer;
     ....
}

Here's where it's used:

void initializeZBuffer(Properties* props){
    //Destroy old zBuffer 2D array (if it's already been initialized)
    if (sizeof props->zBuffer[0] >= 0){
        for (int i = 0; i < props->clientRect.Height(); i++){
            delete[] props->zBuffer[i];
        }
        delete[] props->zBuffer;
    }
    //Create new zBuffer 2D array
    props->zBuffer = new double*[props->clientRect.Height()]; //zBuffer height x width
    for (int i = 0; i < props->clientRect.Height(); i++){
        props->zBuffer[i] = new double[props->clientRect.Width()];
    }
}

My goal is to create an array that holds a z value for every x y pixel on the screen.

The problem in my code is: I check to see if the array has any data in it - it shouldn't on the first iteration, but it does. For some reason, every slot holds a size of 4.

For example, when debugging at that point:

sizeof props->zBuffer[1]  ----->  returns 4
sizeof props->zBuffer[100]  ----->  returns 4
sizeof props->zBuffer[1000000]  ----->  returns 4
sizeof props->zBuffer[10000000000]  ----->  returns 4

and

  sizeof props->zBuffer[1][1]  ----->  returns 4
    sizeof props->zBuffer[100][100]  ----->  returns 4
    sizeof props->zBuffer[1000000][1000000]  ----->  returns 4
    sizeof props->zBuffer[10000000000][10000000]  ----->  returns 4

Since it has a size of 4, naturally I try to see what's in props->zBuffer[3] (the last slot), but I get an error that

ds->zBuffer[3]
CXX0030: Error: expression cannot be evaluated

Does anyone have any clue what is going on? I am totally baffled and frustrated :(

CodyBugstein
  • 21,984
  • 61
  • 207
  • 363

1 Answers1

1

The sizeof operator yields the number of bytes in the object representation of its operand.

Let's look at sizeof(props->zBuffer[1]) for example. Firstly, props->zBuffer[1] is equivalent to *(props->zBuffer + 1). If we add 1 to a double**, we still have a double**, and if we then dereference it, we get a double*. You then take the sizeof that. On your machine, a double* takes up 4 bytes. That's the object representation of a double* - the number of bytes required to store the address of a double.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • Thanks for the explanation. So how do I find the sizeof an array? – CodyBugstein Dec 20 '13 at 09:19
  • @Imray You need to store the size somewhere when you allocate the array so you can look it up later. I recommend instead using standard library container types, such as `std::vector`, rather than doing the allocation yourself. – Joseph Mansfield Dec 20 '13 at 11:07