Maciej S
Maciej S

Reputation: 197

c++ iterate over multidimensional array

Here is an example of iterating over multidimensional array. It works as I checked (compiled using g++ 4.8.1). My question is: why does it work? Why element following the last element of array is a pointer to NULL pointer?

struct Test {
    int i;
};

Test** tab = new Test*[12];
for (int i=0; i<12; ++i) {
    tab[i] = new Test();
    tab[i]->i = i;
}
while (*tab != NULL) {
    std::cout<<(*tab)->i<< std::endl;
    ++tab;
}    

Upvotes: 1

Views: 146

Answers (1)

merlin2011
merlin2011

Reputation: 75555

You are seeing the side effect of the compiler trying to align the stack to a particular multiple of bytes boundary. When it does this, you will see zero-padding after a buffer.

Consider the program below, where I have tried to capture the essence of the question without as much extraneous looping.

#include <stdio.h>


#define SIZE 12
struct Test {
    int i;
};

int main(){
    Test** tab = new Test*[SIZE];
    for (int i=0; i<SIZE; ++i) {
        tab[i] = new Test();
        tab[i]->i = i;
    }
    printf("%p\n", *(tab + SIZE));
}

If you change #define 12 to #define 13 on my system, the output will no longer be nil.

This implies that it does not deterministically work, and you did indeed get lucky.

Upvotes: 2

Related Questions