简体   繁体   中英

Improper Initialization of 2D Array in C

I am trying to construct a 2D array for an assignment. I've used a nested for loop to construct the 2D array using scanf():

  int width;
  int height;

  scanf("%d %d",&width,&height);

  int array[width][height];

  for (int i=0;i<height;i++){
    for (int j=0;j<width;j++){
      scanf("%d",&array[i][j]);
    }
  }

However when I print the array, I can see that it has been constructed in a strange way, where all the numbers of the first line past a certain point are the first few numbers from the second line (instead of what they should be). The next lines after work fine.

Example:

Input:

6 2

1 3 5 7 9 1

2 4 6 8 0 2

3 4 2 0 1 3

The created array looks like this:

1 3 2 4 6 8 (<-- these last 4 numbers are the first 4 numbers of the second line)

2 4 6 8 0 2 (correct)

3 4 2 0 1 3 (correct)

Any ideas? Thanks a lot.

Your declaration of array

int array[width][height];

is wrong. The outer loop goes from 0 to height - 1 , but array[i] can only go from 0 to width - 1 . The same applies for the inner loop. You swapped width and height in the declaration of the array, it should be

int array[height][width];

Also note that for the matrix

1 3 5 7 9 1
2 4 6 8 0 2
3 4 2 0 1 3

the width is 6 and the height is 3, so the correct input should be

6 3
1 3 5 7 9 1
2 4 6 8 0 2
3 4 2 0 1 3

I compiled and run this code:

#include <stdio.h>

int main(void)
{
    int width;
  int height;

  scanf("%d %d",&width,&height);

  int array[height][width];

  for (int i=0;i<height;i++){
    for (int j=0;j<width;j++){
      scanf("%d",&array[i][j]);
    }
  }

  printf("----------------\n");

  for (int i=0;i<height;i++){
    for (int j=0;j<width;j++){
      printf("%d ", array[i][j]);
    }
    printf("\n");
  }


}

And the output is:

$ ./b 
6 3
1 3 5 7 9 1
2 4 6 8 0 2
3 4 2 0 1 3
----------------
1 3 5 7 9 1 
2 4 6 8 0 2 
3 4 2 0 1 3 

as you can see, now it's reading correctly. See https://ideone.com/OJjj0Y

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM