Something seems to be wrong with my trying to use a pointer to a pointer to create a dynamic array. I have several dynamic arrays and I perform the same operations on them, so I want to have a function and pass the arrays as parameters so I don't have redundant code. But for some reason it simply doesn't work. The arrays get built wrong and it seems to cause my game to behave very strangely (like some solid tiles being solid and others not).
Is there something wrong with this code?
void readTiles(int** array, int* total, int* j, int tileSet, BITMAP* magic) { *total = getr(getpixel(magic,*j,tileSet))/8; // size of array *array = new int[*total]; // pointer to a pointer, make the dynamic array for (int i = 0; i < *total; i++) // the operations { if (getg(getpixel(magic,*j,tileSet))) (*array)<i> = getg(getpixel(magic,*j,tileSet))/8; else (*array)<i> = -1; *j++; } }
And an example of me calling the function:
int* solid; int solidTotal, j = 0, tileSet = 0; BITMAP* magic = load_bitmap(); readTiles(&solid, &solidTotal, &j, tileSet, magic);
*j++;
(*j)++;
XD
Thanks a lot Simon, it works now. I didn't think I would need parenthesis there because you don't need them for the =operator. Oh well.
The code *j++; is ambiguous if you do not know C's operator-precedence order. It could either mean *(j++) (increment the pointer j and then get the contents of the new position of the pointer) or (*j)++; (increment the contents of the value pointed to by j). Without the brackets, this operation has the effect of *(j++).
AE.
Thanks a lot Simon, it works now. I didn't think I would need parenthesis there because you don't need them for the =operator. Oh well.
Have made this mistake several times myself.. very annoying.
However, ++*j; wouldn't need () around it.
The evils of terse code.
When in doubt, use parentheses. When not in doubt, use parentheses. Since you're using C++ anyhow, you could have used a reference instead of a pointer and avoided the whole mess. Not a critism, really, just a thought.