Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Multidimensional arrays and pointers in C
#1
Okay, this question isn't a problem I have, it's a complete blank I draw when trying to comprehend how it would be done...
I know how to use arrays and pointers in C. I'm very comfortable with them now:
Code:
#include <stdio.h>
void pass_array(int *array, int length);
int main() {
int array[3]={1,2,3};
pass_array(array,3);  /* could be pass_array(&array[0]), too */
return 0;
}
void pass_array(int *array)
{
int i;
for (i=0; i<3; i++)
printf("%d",*(array+i));   /* could be array++ or array[i] as well */
}
That's a simple function that takes an array and prints it out.
Well, I have absolutely no idea how to use pointers with multdimensional arrays. My book just touches that lightly, but I don't understand.
So if I wanted to have a function that took a pointer to a multidimensional array (say, a map for a game), and fill that map with the correct signifigant values for tiles in the game...how would I do it?
f only life let you press CTRL-Z.
--------------------------------------
Freebasic is like QB, except it doesn't suck.
Reply
#2
Two Dimensional array:
Code:
void pass_array(int (*array)[Size2]) {

for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
  printf("%d",*(*(array+i)+j));
}

'Size2' is the size of the second dimension of the array 'array'
B 4 EVER
Reply
#3
Just to back akooma's stuff:

Think on 2D arrays as arrays of arrays. So you have a pointer to a set of pointers that point to a set of data, or what's the same, you have a array of pointers.

You can try the easy version:

Code:
void pass_array(int array[3][3])
{
   for (int i=0; i<3; i++)
      for (int j=0; j<3; j++)
         printf("%d", array[i][j]);
}
SCUMM (the band) on Myspace!
ComputerEmuzone Games Studio
underBASIC, homegrown musicians
[img]http://www.ojodepez-fanzine.net/almacen/yoghourtslover.png[/i
Reply
#4
I didn't know it was that simple! Big Grin
Thanks, mates...
f only life let you press CTRL-Z.
--------------------------------------
Freebasic is like QB, except it doesn't suck.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)