简体   繁体   English

在C中声明大小数组

[英]declaring size array in c

as much as i know the next code should not run. 据我所知,下一个代码不应运行。

The first problem is declaring 'int i' inside the loop and not at the start code. 第一个问题是在循环内部而不是起始代码中声明“ int i”。

The next problem is the array size is defined in run time and therefor we must use dynamiclly allocation. 下一个问题是数组大小是在运行时定义的,因此我们必须动态使用分配。

I was expected to get "segment fualt". 预计我会得到“段fualt”。

I run it with the command: 我使用以下命令运行它:

gcc -Wall commandLineArgument.c -o ex1

int main(void){
  int size=0;
  printf("enter number:\n");
  scanf("%d",&size);
  printf("The size is: %d\n",size);
  int arr[size];
  for(int i= 0;i<size;i++)
  {
    arr[i] = 5;
  }

  for(int i= 0;i<size;i++)
  {
    printf("%d,",arr[i]);
  }  
  printf("\n");
  return 0;}

edit if variable length arrays have been supported in C since C99 then how the update code running? 编辑是否从C99开始在C中支持可变长度数组,那么更新代码如何运行?

gcc -Wall -std=c89 commandLineArgument.c -o ex1 

int main(void){
int i;
int size=0;
printf("enter number:\n");
scanf("%d",&size);
printf("The size is: %d\n",size);
int arr[size];
printf("The size of arr: %lu\n",sizeof(arr));
for(i= 0;i<size;i++)
{
    arr[i] = 5;
}

for(i= 0;i<size;i++)
{
    printf("%d,",arr[i]);
}    
printf("\n");
return 0;}

This is anachronistic: your code has been valid C since and including C99. 这是不合时宜的:自从C99(包括C99)以来,您的代码一直是有效的C。

Since at least C99 you are able to declare i locally in the for loop. 由于至少C99,您可以在for循环中本地声明i

And variable length arrays have been supported in C since C99. 从C99开始,C语言就支持可变长度数组 (Note that this is not supported even in C++17). (请注意,即使在C ++ 17中也不支持此功能)。

It looks like you are using an old version of gcc. 看来您使用的是旧版的gcc。

The two features you are trying to use were added in C99. 您尝试使用的两个功能已在C99中添加。 The default for gcc versions older than version 5 is to compile using the old C89 standard. 早于版本5的gcc版本的默认设置是使用旧的C89标准进行编译。 To use features added in later standards you need to explicitly tell older versions of gcc to use a newer standard. 要使用在更高标准中添加的功能,您需要明确告知旧版gcc使用新标准。

The compiler option -std=c11 instructs gcc to use the current C11 standard. 编译器选项-std=c11指示gcc使用当前的C11标准。 The minimum you need is -std=99 . 您所需的最小值是-std=99

I would recommend that you tell gcc to use the current standard: 我建议您告诉gcc使用当前标准:

 gcc -Wall -std=c11 commandLineArgument.c -o ex1

Another way to solve your problem is to upgrade to gcc v5 or newer. 解决问题的另一种方法是升级到gcc v5或更高版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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