5

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;
}
3
  • 6
    You declare your array of variable length m before m has a meaningful value. Put that declaration after the first scanf. Commented Oct 24, 2014 at 14:54
  • @MOehm I can't believe I just spent two hours trying to find out what is wrong and missing that. Thanks a lot! Commented Oct 24, 2014 at 14:58
  • Well, the proverbial fresh set of eyes ... Commented Oct 24, 2014 at 14:59

3 Answers 3

2

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];
Sign up to request clarification or add additional context in comments.

Comments

1

This is the place where you messed up.

int m;
int array[m][m];

Here ,m is uninitialized and you are creating an array of m*m elements. You need m initialized before the declaration of the array. So move the array declaration after the scanf just after it so that m gets initialized before you declare the array.

Comments

0
#innclude <stdio.h>

int i, j;
int t[5][5];
i=0;
j=0;

while(i < 5)
{
    j = 0;
    while (j < 5)
    {
        scanf("%d", &(t[i][j++]));
    }
    i++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.