0

I'm trying to add values inside a matrix. For the first row everyting goes well. However, when I'm trying to access the second row (if there's one), I get an invalid write.

Here is the the different version I wrote :

  1. mat[i][j]
  2. *(*(mat + i) + j)
  3. mat[i * N + j]
int** matrice(int N, int M){
    int **mat = (int **)malloc(N * sizeof(int*));
    for(int i = 0; i < N; i++) mat[i] = (int *)malloc(M * sizeof(int));

    for (int i = 0; i < N; i++){
        for (int j = 0; i < M; j++){
            //mat[i][j] = i+j;
        }
    }

    return mat;
}
  • Also be careful, `malloc` doesn't initialize the memory it allocates, the data you won't explicitly initialize will contain *indeterminate* (seemingly random or garbage) values. – Some programmer dude Sep 09 '19 at 12:22
  • And in C you [don't need to cast the result of `malloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Some programmer dude Sep 09 '19 at 12:23
  • 3
    voting to close as a simple typo : `i < M` instead of `j < M` – Sander De Dycker Sep 09 '19 at 12:28
  • 1
    Related: [Correctly allocating multi-dimensional arrays](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays) – Lundin Sep 09 '19 at 12:42

1 Answers1

0

You have an error in your nested for loop that uses j as index, however, you compare with i:

for (int j = 0; i < M; j++)

should be

for (int j = 0; j < M; j++)
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41