C - Getting values in a two-dimensional array with pointer and for loop

Description

Getting values in a two-dimensional array with pointer and for loop

Demo

#include <stdio.h>

int main(void)
{
  char matrix[3][3] = {
    { '1','2','3' },
    { '4','5','6' },
    { '7','8','9' }
  };/*from  w  w w . j  a  v a2 s .  c  o m*/

  // List all elements of the array
  for (int i = 0; i < 9; ++i)
    printf(" matrix: %c\n", *(*matrix + i));
  return 0;
}

Result

We dereference matrix in the loop:

printf(" matrix: %c\n", *(*matrix + i));

You use the expression *(*matrix + i) to get the value of an array element.

*matrix + i produces the address of the element in the matrix array that is at offset i.

Using matrix (array name) is the same as using an address value of type char**.

Dereferencing matrix produces the same address value, but of type char*.

Related Topic