-3

I'm doing a project and need the user to input a series of chars to fill a matrix. This is the code I've written:

#include <stdio.h>
#include <string.h>

int main(void) {

  int i, j;

  getchar(); 
  scanf(" %i %i", &i, &j);
  
  char matrix[i][j];
  
  for (int a = 0; a < i; a++) {
      char temp[j];
      memset(temp, 0, j);
      getchar();

      fgets(temp, j, stdin);

      scanf("%c", temp);
      
      for (int b = 0; b < j; b++) {
        matrix[a][b] = temp[b];
      }
  }
return 0;
}

The error displayed was: signal: segmentation fault (core dumped), and I'm not sure how to fix it

li_a
  • 1
  • 1
    Why are you reading one line/row of input into `temp` with `fgets(temp, j, stdin);`, but then attempting to overwrite `temp` in the next line of code? – Andreas Wenzel Oct 06 '22 at 10:32
  • Why are you calling `getchar` at the start of the program, which discards the first character on standard input. What is the significance of this character? – Andreas Wenzel Oct 06 '22 at 10:34
  • What input do you provide to that program? When you run your program in a debugger, where do you get the segmentation fault? What values do the involved variables hold? – Gerhardh Oct 06 '22 at 10:41
  • Have you tried running your code line-by-line in a debugger while monitoring the values of all variables, in order to determine in which line your program stops behaving as intended? If you did not try this, then you may want to read this: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/12149471) You may also want to read this: [How to debug small programs?](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Andreas Wenzel Oct 06 '22 at 10:42

1 Answers1

1

I recommend you don't mix scanf(), getchar() and fgets(). If the input is line-based, use only fgets() to read in lines from the input into a buffer, and use sscanf() or other methods to parse that buffer further if it contains multiple items. For example:

char line[1000];
int i, j;

fgets(line, sizeof line, stdin);
sscanf(line, "%d %d", &i, &i);

char matrix[i][j];

for (int a = 0; a < i; a++) {
  fgets(line, sizeof line, stdin);

  for (int b = 0; b < j; b++) {
    matrix[a][b] = line[b];
  }
}

Note that the above code still has some issues you might want to think about: the buffer has a fixed size, so it can only handle matrices of 999 columns wide. Furthermore, there is no error checking; you might want to check the return value of fgets() and sscanf() to check if the input was read correctly, and also check that each line read inside the outer for-loop has at least j characters in it.

G. Sliepen
  • 7,637
  • 1
  • 15
  • 31