Home > Back-end >  Why isn't scanf storing integers in the right array location?
Why isn't scanf storing integers in the right array location?

Time:10-05

I'm creating a dynamically allocated two dimensional int array and trying to use scanf to read user input directly to it, however this doesn't work properly. The first read is correct and stores the user entered value at [0][0], but the second read stores the value at [1][0] instead of [0][1], and the third and subsequent reads don't store the values anywhere in the array (I guess ending up in random memory outside the bounds?). It seems like the indices are wrong, but I've double checked them and can see the correct values for them in the debugger.

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

#define ROW_SIZE 2
#define COL_SIZE 6

typedef int myMatrix[ROW_SIZE][COL_SIZE];

int main(void) {
  myMatrix *pMatrix = (myMatrix *)malloc(sizeof(int) * (ROW_SIZE * COL_SIZE));

  for (int i = 0; i < ROW_SIZE;   i) {
    for (int j = 0; j < COL_SIZE;   j) {
      printf("Enter row %d column %d: ", i, j);
      scanf("%d", pMatrix[i][j]);
    }
  }

  // Do stuff with matrix

  return 0;
}

If I read the user input into a temp int and then write that to the de-referenced array pointer it works fine:

  int temp = 0;
  for (int i = 0; i < ROW_SIZE;   i) {
    for (int j = 0; j < COL_SIZE;   j) {
      printf("Enter row %d column %d: ", i, j);
      scanf("%d", &temp);
      (*pMatrix)[i][j] = temp;
    }
  }

What am I doing wrong with scanf and the 2d array pointer?

CodePudding user response:

pMatrix is a pointer to a 2D array.

So pMatrix[0] will bring you to the first allocated 2D array,

and pMatrix[1] will bring you to the second allocated 2D array,

and pMatrix[2] will bring you to the third allocated 2D array,

and so on.

In your code you only allocate one 2D array so accessing pMatrix[1], pMatrix[2], ... is illegal as it is outside the allocated memory.

In other words

scanf("%d", pMatrix[i][j]);

is wrong. You need an extra dereference to get to the individual integers and a & to take its address so that it can be used in scanf.

You can do:

scanf("%d", &pMatrix[0][i][j]);  // [0] because you only allocate 1 2D array

or

scanf("%d", &(*pMatrix)[i][j]);  // (*pMatrix) works just like pMatrix[0]
                                 // The ( ) is important due to
                                 // operator precedence.

They are the same.

  • Related