Question

I am breaking my head on this but cannot proceed so please help. Working on a programming assignment:

INPUT:
First line contains a value N representing the dimension of the input matrix, followed by N lines, each line representing a row of the matrix. Within each row, N values are given and are separated by whitespace.

So instead of using fgets() and then extracting the digits using strtol() I am forced to use scanf() because the assignment platform does not work properly with strtol().

This is my program:

int main()
{
   int N;
   int arr[N][N];
   int idx1, idx2=0;

   scanf("%d ",&N);

   for (idx1=0; idx1<N; idx1++) {
      for(idx2=0; idx2<N; idx2++) {
         scanf("%d", &arr[idx1][idx2]);
         printf("arr[%d][%d]=%d ", idx1, idx2, arr[idx1][idx2]);
      }
   }
   printf("\n");
   for (idx1=0; idx1<N; idx1++) {
      for(idx2=0; idx2<N; idx2++) {
         printf("arr[%d][%d]=%d ", idx1, idx2, arr[idx1][idx2]);
      }
   }

   return 0;
}

Output:

3
1 2 3
arr[0][0]=1 arr[0][1]=2 arr[0][2]=3 
4 5 6
arr[1][0]=4 arr[1][1]=5 arr[1][2]=6 
7 8 9
arr[2][0]=7 arr[2][1]=8 arr[2][2]=9 
arr[0][0]=1 arr[0][1]=4 arr[0][2]=7 arr[1][0]=4 arr[1][1]=7 arr[1][2]=8 arr[2][0]=7 arr[2][1]=8 arr[2][2]=9

FWIW gcc --version gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3

Why is the second output not matching the first? What am i missing here?

Was it helpful?

Solution

int N;
int arr[N][N];
int idx1, idx2=0;

scanf("%d ",&N);

You have to declare arr after you write N object. Here when arr is declared, N value is indeterminate.

OTHER TIPS

If you want to create a variable length array like that, you need to dynamically allocate it instead of creating an array of size N (N has some garbage value at the time) and then changing the size of it based on user input. Use malloc or calloc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top