gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

Beginners > Very simple array question

#10482 - goro - Sat Sep 06, 2003 11:58 am

Please don't cuss me for being dumb but I've been learning/coding for
too many hours so my brain is probably fried.

Code:


//create an OAM variable and make it point to the address of OAM
u16* OAM = (u16*)0x7000000;

//Copy our sprite array to OAM
void CopyOAM()

    u16 loop; 
    u16* temp; 
    temp = (u16*)sprites; 
   
    for(loop = 0; loop < 128*4; loop++) 
    {
        OAM[loop] = temp[loop]; 
     }
}


temp is a pointer to a u16 (unsigned int)
and OAM is a pointer to the address of OAM

but in the 'for loop' they are treated as arrays and data is copied from
one to the other.

Is this some form of sorcery?

#10485 - tepples - Sat Sep 06, 2003 1:58 pm

In C and C++, any ordinary pointer can be treated as if it were a pointer to the first element of an array. The compiler can do the array indexing calculations correctly because it knows the type of what the pointer points to and how big it is.
_________________
-- Where is he?
-- Who?
-- You know, the human.
-- I think he moved to Tilwick.

#10490 - goro - Sat Sep 06, 2003 2:37 pm

so if it points to sprites[index] and index = 0, then when index is incremented and the loop completes a cycle, does it effectively point to sprites[1]?

#10494 - tepples - Sat Sep 06, 2003 3:42 pm

Pretty much.
Code:
{
  Actor baddies[20];
  Actor *cur = baddies;
  /* now, cur points to baddies[0] */

  cur++;
  /* now, cur points to baddies[1] */

  cur += 5;
  /* now, cur points to baddies[6], and e.g. cur[9] would be baddies[15] */
}

Quick tip: foo[0] is nearly equivalent to *foo, and foo[0].bar is nearly equivalent to foo->bar. Use whatever makes more sense in the context of your code.

A quick Google search (c arrays pointers) gives this tutorial.
_________________
-- Where is he?
-- Who?
-- You know, the human.
-- I think he moved to Tilwick.

#10501 - goro - Sat Sep 06, 2003 5:25 pm

Wow.

Thanks for clearing all that up.

I'll study that tutorial straight away. more brain-food.

Thanks Tepples.