Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 具有可变长度数组的奇怪输出?_C_Gcc_Variable Length Array - Fatal编程技术网

C 具有可变长度数组的奇怪输出?

C 具有可变长度数组的奇怪输出?,c,gcc,variable-length-array,C,Gcc,Variable Length Array,我在这件事上伤了脑筋,但无法继续,所以请帮忙。 从事编程作业: 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.

我在这件事上伤了脑筋,但无法继续,所以请帮忙。 从事编程作业:

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.
因此,我没有使用fgets()然后使用strtol()提取数字,而是被迫使用scanf(),因为赋值平台不能正确使用strtol()

这是我的节目:

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;
}
FWIW gcc——版本 gcc(Ubuntu/Linaro 4.6.3-1ubuntu5)4.6.3

为什么第二个输出与第一个不匹配?我错过了什么

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

scanf("%d ",&N);

写入
N
对象后,必须声明
arr
。在这里,当声明
arr
时,
N
值是不确定的。

如果要创建这样的可变长度数组,需要动态分配它,而不是创建大小为N的数组(N当时有一些垃圾值),然后根据用户输入更改其大小。使用malloc或calloc。

为什么在scanf中的转换说明符后会有空格?谢谢,之前已经想到了,但没有尝试过。获取用户输入,然后使用
int arr[N][N]
创建数组很好。问题是,它正在创建一个大小为[N][N]的数组,其中N尚未初始化,据我所知,这是一种糟糕的做法是的,但正如我的评论所暗示的那样,先初始化或分配N,然后创建数组是一种不错的做法;国际航空公司[N][N];这就是我所说的不好的做法,N有一个垃圾值,用它创建一个2D数组是不好的做法,即使它后来改变了,我们同意
int N;国际航空公司[N][N]是不好的做法。我的意思是,用
intn;scanf(“%d”和“&N”);国际航空公司[N][N]--如果我们还包括一些错误检查,以确保
N
输入正确。因此,您不需要使用malloc。
int N;
int arr[N][N];
int idx1, idx2=0;

scanf("%d ",&N);