0

I am new to C and I don't understand why I am not able to easily populate a 2d array.

Here is my code: one function populates the matrix and the other displays it.

#include <stdio.h>

int matrix[5][5];
int size = 5;

void fill_matrix() {
    for(int k=0; k<size; k++) {
        for(int l=0; l<size; l++) {
            matrix[k][l] = k + l;
        }
    }
}

void print_matrix() {
    for(int k=0; k<size; k++) {
        for(int l=0; l<size; l++) {
            printf("%d ", *matrix[k,l]);
        }
        printf("\n");
    }
}

int main() {
    fill_matrix();
    print_matrix();
}

And the result is this

0 1 2 3 4 
0 1 2 3 4 
0 1 2 3 4 
0 1 2 3 4 
0 1 2 3 4 

Instead of this

0 1 2 3 4 
1 2 3 4 5 
2 3 4 5 6 
3 4 5 6 7 
4 5 6 7 8 

I know that the answer is probably extremely simple, but I was't able to find a solution after few hours so here I am.

Kipr
  • 806
  • 10
  • 13

1 Answers1

0

What you meant to do was matrix[k][l] to address the row and column of the matrix.

Instead, what you have, *matrix[k,l]. What is happening here is the comma operator is being used in the expression to index the array. The result of the expression is equal to that of the right-side of the comma operator, so effectively what you have is *matrix[l]. matrix[l], using only one index for a two dimensional array, points you to the lth row of the array, so it is essentially of type int[5]. Then when you dereference it with the asterisk, you are grabbing the contents of the first element of that row.

Christian Gibbons
  • 4,272
  • 1
  • 16
  • 29
  • Indeed, I was confused by the fact that no warning was coming from the compiler about the comma syntax (that is valid in some languages). I thought it was some kind of Pythonic copy error and that the first row was replicated throughout the whole matrix. Thanks – Kipr Sep 25 '19 at 08:42