Qbasicnews.com

Full Version: Multidimensional arrays and pointers in C
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
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'
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]);
}
I didn't know it was that simple! Big Grin
Thanks, mates...