0

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?

user138645
  • 772
  • 1
  • 7
  • 18

2 Answers2

4
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.

ouah
  • 142,963
  • 15
  • 272
  • 331
-2

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.

  • 1
    It's fine to get the user input and then create the array with `int arr[N][N]`. – M.M Mar 23 '14 at 01:08
  • The thing is, it's creating an array of size [N][N] where N hasn't been initialized, which from what I've learned, is terrible practice – user3449281 Mar 23 '14 at 01:13
  • Yes, but it is OK practice to initialize or assign N first and then create the array, as my comment suggests – M.M Mar 23 '14 at 01:20
  • int N; int arr[N][N]; This is what I am talking about being bad practice, N has a garbage value and creating a 2D array off of that is bad practice, even if it changes later – user3449281 Mar 23 '14 at 01:31
  • 1
    We agree that `int N; int arr[N][N];` is bad practice. I am saying that it is OK practice to instead do `int N; scanf("%d", &N); int arr[N][N];` -- if we also include some error-checking that `N` was input correctly. As such, you don't need to use malloc. – M.M Mar 23 '14 at 01:34