Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » Pointer to a Pointer

Credits go to Simon Parzer for helping out!
This thread is locked; no one can reply to it. rss feed Print
Pointer to a Pointer
Jeff Bernard
Member #6,698
December 2005
avatar

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);

--
I thought I was wrong once, but I was mistaken.

Simon Parzer
Member #3,330
March 2003
avatar

Quote:

*j++;

(*j)++;

Jeff Bernard
Member #6,698
December 2005
avatar

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.

--
I thought I was wrong once, but I was mistaken.

Andrei Ellman
Member #3,434
April 2003

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.

--
Don't let the illegitimates turn you into carbon.

Simon Parzer
Member #3,330
March 2003
avatar

Quote:

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.

BAF
Member #2,981
December 2002
avatar

However, ++*j; wouldn't need () around it.

_Dante
Member #7,398
June 2006
avatar

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.

-----------------------------
Anatidaephobia: The fear that somehow, somewhere, a duck is watching you

Go to: