且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态内存分配在C没有的malloc

更新时间:2023-11-15 14:50:16

添加 -pedantic 来你的编译选项(例如, -Wall -std = C89 -pedantic )和 GCC 会告诉你:

警告:ISO C90禁止变长数组'改编'

这意味着你的程序的确不是C89 / C90标准。

更改为 -pedantic -pedantic-错误 GCC 将停止翻译。

Here's a C program one of my friends had written. From what I know, arrays had to be initialised at compile time before C99 introduced VLA's, or using malloc during runtime.

But here the program accepts value of a const from the user and initialises the array accordingly. It's working fine, even with gcc -std=c89, but looks very wrong to me. Is it all compiler dependent?

#include <stdio.h>

int
main()
{
 int const n;
 scanf("%d", &n);
 printf("n is %d\n", n);
 int arr[n];
 int i;
 for(i = 0; i < n; i++)
   arr[i] = i;
 for(i = 0; i < n; i++)
   printf("%d, ", arr[i]);
 return 0;
}

Add -pedantic to your compile options (e.g, -Wall -std=c89 -pedantic) and gcc will tell you:

warning: ISO C90 forbids variable length array ‘arr’

which means that your program is indeed not c89/c90 compliant.

Change with -pedantic with -pedantic-errors and gcc will stop translation.