Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Scanf for Storing Input in 2d Arrays

I want to scan input and save it in a square 2d array.

The first two digits are saved in seperate variables, the first digit is a target number (irrelevant here), the second digit gets saved in variable m, i.e. m = 5 in this case. m is the number of rows/colums of the square matrix. The rest of the input should be saved in the array. For this particular input, I get a segmentation-fault and random numbers are printed on the screen. I used some printf statements to trace where things go wrong, and I noticed that the index i in the first loop jumped from 2 to 11 in one scenario, for other input it jumped to 33. Thanks for your help! I hope I am not missing an obvious mistake.

Input: (each row is seperated by the previous by pressing enter.)

42 5

0 3 7 9 10

9 13 20 5 20

12 11 33 0 12

17 39 22 3 18

My code:

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

int main (int argc, char* arv[]){

  int target;               // for later processing, irrelevant here
  int m;                    // m = #rows and #columns of array
  int array[m][m];
  scanf("%d %d", &target, &m);
 
  int i, k;
  for(i = 0; i < m; i++){
    for(k = 0; k < m; k++){
       scanf("%d", &(array[i][k]));    // save value in array.
    }
  }
                                      // the problem occurs before this point.
  for(i = 0; i < m; i++){
     for(k = 0; k < m; k++){
       printf("%2d", array[i][k]);    // print array.
     }
     printf("\n");
  }  

  return 0;
}
like image 396
SQU901 Avatar asked Oct 31 '22 15:10

SQU901


1 Answers

You have not initialized the value of m before creating array[m][m]. Without initializing, the value of m can be anything.

Change:

int array[m][m];
scanf("%d %d", &target, &m);

to

scanf("%d %d", &target, &m);
int array[m][m];
like image 189
ani627 Avatar answered Nov 10 '22 13:11

ani627