c - Using Scanf for Storing Input in 2d Arrays -



c - Using Scanf for Storing Input in 2d Arrays -

i want scan input , save in square 2d array.

the first 2 digits saved in seperate variables, first digit target number (irrelevant here), sec digit gets saved in variable m, i.e. m = 5 in case. m number of rows/colums of square matrix. rest of input should saved in array. particular input, segmentation-fault , random numbers printed on screen. used printf statements trace things go wrong, , noticed index i in first loop jumped 2 11 in 1 scenario, other input jumped 33. help! hope not missing obvious mistake.

input: (each row seperated previous 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; // later processing, irrelevant here int m; // m = #rows , #columns of array int array[m][m]; scanf("%d %d", &target, &m); int i, k; for(i = 0; < m; i++){ for(k = 0; k < m; k++){ scanf("%d", &(array[i][k])); // save value in array. } } // problem occurs before point. for(i = 0; < m; i++){ for(k = 0; k < m; k++){ printf("%2d", array[i][k]); // print array. } printf("\n"); } homecoming 0; }

you have not initialized value of m before creating array[m][m]. without initializing, value of m can anything.

change:

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

to

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

c arrays segmentation-fault scanf multidimensional-array

Comments

Popular posts from this blog

php - Edges appear in image after resizing -

ios8 - iOS custom keyboard - preserve state between appearances -

Delphi change the assembly code of a running process -