How to traverse a 2-D array in C and display?

2

In this code, I have an array of two dimensions, I started and I want to start with printf, but I do not know how to do it:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i;
    int matriz1 [3][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
    int matriz2 [3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

    for(i=0; i<12; i++) {
        printf("%d\n", matriz1[i]);

    }

  system("pause");
  return 0;

}

I tried with for

asked by anonymous 17.05.2015 / 02:33

1 answer

1

Compile your program with warnings (option -Wall ) that the compiler will give you a hint of what is wrong.

The problem you have is that a two-dimensional array must be accessed using matriz[i][j] , where i and j are the row and column indexes, respectively. What's happening in your code is that matriz[i] is a pointer to the i-th array line and your printf is casting that pointer to a number. You are also trying to access rows from the array that do not exist (which in C results in undefined behavior)

The easiest way to go through the array correctly is with a pair of loops:

for(int i=0; i<3; i++){
    for(int j=0; j<4; j++){
        printf("%d ", matriz[i][j]);
    }
    printf("\n");
}
    
17.05.2015 / 02:37