c arrays 2d

Understanding Arrays and Pointers and 2D Arrays in C

roland's picture
Have a look at the following code:
#include 
#include 

int **array;
int array_dim1 = 5, array_dim2 = 6;

int main() {
  // Declare Vars
  int i, j;

  // Allocate Memory
  array = (int **)malloc(array_dim1*sizeof(int *));
  for(i = 0; i < array_dim1;  i++) {
    array[i] = (int *)malloc(array_dim2*sizeof(int));
    for(j = 0; j < array_dim2; j++)
      array[i][j] = i*array_dim2+j;
  }
  for(i = 0; i < array_dim1; i++) {
    for(j = 0; j < array_dim2; j++) {
      printf("%d\t", array[i][j]);
    }
    printf("\n");
  }

  int *k = array[2];
  for(i = 0; i < 2; i++)
    printf("k: %d\n", k[i]);

  // Free Memory
  for(i = 0; i < array_dim1;  i++)
    free(array[i]);
  free(array);

  return 0;
}
It will print out
0	1	2	3	4	5	
6	7	8	9	10	11	
12	13	14	15	16	17	
18	19	20	21	22	23	
24	25	26	27	28	29	
k: 12
k: 13
So, you can point a pointer to a 2D array and iterate over it as if it were a regular 1D array. Cool eh?
Syndicate content