Why is my array of indices from 0-16129 is not null but the rest are?

91 views Asked by At

I have an array of indices with a length of 97536, when it gets to 16,129 it gives me a null pointer exception. Index[] indices = new Index[6 * (VERTEX_COUNT - 1) * (VERTEX_COUNT * 1)];. I then have a double for loop and a pointer to loop through all of the objects in the array and initial them.

int pointer = 0;

    for(int gz = 0; gz < VERTEX_COUNT - 1; gz++)
    {
        for(int gx = 0; gx < VERTEX_COUNT - 1; gx++)
        {
            indices[pointer] = new Index((gz * VERTEX_COUNT) + gx);
            indices[pointer] = new Index(((gz + 1) * VERTEX_COUNT) + gx);
            indices[pointer] = new Index(((gz * VERTEX_COUNT) + gx) + 1);
            indices[pointer] = new Index(((gz * VERTEX_COUNT) + gx) + 1);
            indices[pointer] = new Index(((gz + 1) * VERTEX_COUNT) + gx);
            indices[pointer] = new Index((((gz + 1) * VERTEX_COUNT) + gx) + 1);
            pointer++;
        }
    }

This error did not come up when the array was a int[] indices. I am very confused and wondering why the null pointer exception happens at 16129. The first thought was that the for loops never reach the correct number, if so how would I calculate that? - Thanks in advance

1

There are 1 answers

2
dcsohl On

You say your array is 97536 items. So I deduce VERTEX_COUNT=128. I arrive at this by noticing that 6*127*128 = 97536.

You are running through a nested for loop, where each loop runs from 0 to VERTEX_COUNT-1, or from 0 to 127. 127*127=16129, and as a commenter above pointed out you overwrite the same position in your array 6 times in each inner loop, so you are only instantiating from 0 to 16128. Thus when you try to access position 16129 (and above), you will retrieve null, which naturally throws your NPE if you dereference it without checking.

I'm assuming you don't want to write to the same index six times, but rather six consecutive indices, so my suggestion for fixing this would be

    { // inner loop body
        indices[pointer++] = new Index((gz * VERTEX_COUNT) + gx);
        indices[pointer++] = new Index(((gz + 1) * VERTEX_COUNT) + gx);
        indices[pointer++] = new Index(((gz * VERTEX_COUNT) + gx) + 1);
        indices[pointer++] = new Index(((gz * VERTEX_COUNT) + gx) + 1);
        indices[pointer++] = new Index(((gz + 1) * VERTEX_COUNT) + gx);
        indices[pointer++] = new Index((((gz + 1) * VERTEX_COUNT) + gx) + 1);
        // DO NOT DO pointer++ HERE
    }

I bet you had the same problem when it was an int[] but you never noticed it before because the default value of each item in an int[] is 0 (not null) which will not give you NPEs...