How to scroll through a 2-dimensional matrix in C and display?

Asked

Viewed 3,712 times

2

In this code, I have a two-dimensional array(array), I started and I want to print with the printf, but I don’t know how:

#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 the for i<12 because it is size 12, but it displays other numbers.

  • Your question would be clearer if you showed what are the "other numbers" you are getting as output.

  • I’m trying to get the numbers declared in the matrix.

  • I know what you are getting. It’s just that in general it also helps if you tell what are the wrong numbers that your program is printing.

  • But now I’ve rewritten the code, I don’t know anymore.

  • Don’t worry. It was just a tip for your next question

1 answer

1


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

The problem you have is that a two-dimensional matrix must be accessed using matriz[i][j], where i and j are the indices of the row and column respectively. What is happening in your code is that matriz[i] is a pointer to the i-th row of the matrix and your printf is doing a "cast" of that pointer to a number. You’re also trying to access matrix lines that don’t exist (which in C results in undefined behavior)

The easiest way to traverse the matrix correctly is with a couple of loops:

for(int i=0; i<3; i++){
    for(int j=0; j<4; j++){
        printf("%d ", matriz[i][j]);
    }
    printf("\n");
}
  • Declare variable in for? From error.

  • Modern compilers for C accept declare inside for. If you are using gcc use --std=c11. If you’re using visual studio, change compiler :) But you can declare out if you prefer

  • Yes, I’m using gcc and codeblocks, I was able to solve.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.