Create a two-dimensional array in c

www.lau‮rutt‬i.com
Create a two-dimensional array in c

We will create a two-dimensional integer array "num" with 3 rows and 4 columns.

int num[3][4] = {
  {1, 2,  3,  4},
  {5, 6,  7,  8},
  {9, 10, 11, 12}
};

Create a pointer pointed to a two-dimensional array

We will use the address operator "&" to assign the address of the first element of the array "num" to the pointer "ptr".

int *ptr = &num[0][0];

Accessing the elements of a two-dimensional array using pointer

#include <stdio.h>

int main(void) {
  
  //2d array
  int num[3][4] = {
    {1, 2,  3,  4},
    {5, 6,  7,  8},
    {9, 10, 11, 12}
  };

  //pointer ptr pointing at array num
  int *ptr = &num[0][0];
  
  //other variables
  int
    ROWS = 3,
    COLS = 4,
    TOTAL_CELLS = ROWS * COLS,
    i;
  
  //print the elements of the array num via pointer ptr
  for (i = 0; i < TOTAL_CELLS; i++) {
    printf("%d ", *(ptr + i));
  }
  
  return 0;
}
1 2 3 4 5 6 7 8 9 10 11 12
Created Time:2017-08-28 06:51:43  Author:lautturi