mardi 21 avril 2009

C special on arrays and functions

Introductions of C can be found on the internet. These explain basic stuff like pointrs and arrays. But programming a bit for the nds, you need details which are not in the introductions.

Programming in Programmers Notepad with testing in an emulator (all for the nds in C) is not the easiest way of experimenting. So sometimes i write some test code in Dev Cpp.

This is an example: for one of the field in a minigolf game you need an array. This array must be initiated in a struct. This struct has a function making this initialization. Many possibilities of doing this, of course. One of the possibilitites is shown here:

This is (part of ) the struct: (in a header file)

typedef struct Field{

int pointsList[200];
int roundNr;

}FIELD;

extern FIELD makeField( FIELD myField, int p[ ]);
extern void printField(FIELD myField);

The function is found in the source file: see especially how the array is called. p[ ] is a pointer.

FIELD makeField(FIELD myField, int p[ ], pSize)
{
myField.roundNr = 4;//just some value for this example

int c1;
for ( c1=0; c1 <
pSize ; c1++ )
{
myField.pointsList[c1] = (int)p[c1] ;
printf("value from field make function %d \n " ,(int)p[c1] );
}
return myField; //necessary to get the object back, this is C
}

void printField(FIELD myField)
{
int c1;
for ( c1=0; c1 <>
printf("from print %d \n",(int)myField.pointsList[c1] ) ;
}

then the main file:

#define NUM_ELEM(x) (sizeof (x) / sizeof (*(x))) //this trick is explained see below

int main(int argc, char *argv[])
{
FIELD myField;
int p[ ] = {1,2,3,4,5,6,7,8,9,0};
myField = makeField( myField, p,
NUM_ELEM(p)); //return because of passing by value
printField( myField);//check
}

the
NUM_ELEM is explained in http://en.wikibooks.org/wiki/C_Programming/Pointers_and_arrays#Pointers_in_Function_Arguments
nearly at the end of this page.

You see how the array is passed to the function, how the struct object is filled with the array. All kinds of little C details dealing with the not OO world!

Of course you can do this in another way, not returning the field, you have to use a pointer to this struct:

in the main:

FIELD * myFieldPointer;
myFieldPointer = &secondField;
int p2[] = {11,12,13,14,15,16,17,18,19,20};
makeFieldPointer( myFieldPointer, p2, NUM_ELEM(p2) ); //not returning because of passing by reference
printField( secondField);//check

You need another function
makeFieldPointer:

void makeFieldPointer( FIELD *myFieldPointer, int p[ ], int sizeP)
{
myFieldPointer->roundNr = 4; //need the -> because of the pointer
int c1;
for ( c1=0; c1 <>
{
myFieldPointer->pointsList[c1] = (int)p[c1] ;
printf("value from
makeFieldPointer %d \n " ,(int)p[c1] );
}
}