没有malloc的c中的动态内存分配

这是我的一位朋友写过的C程序。 据我所知,在C99引入VLA之前,或者在运行时使用malloc之前,必须在编译时初始化数组。

但是这里程序接受用户的const值并相应地初始化数组。 它工作正常,即使使用gcc -std=c89 ,但对我来说看起来非常错误。 是否所有编译器都依赖?

 #include  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; } 

添加-pedantic到你的编译选项(例如, -Wall -std=c89 -pedantic )和gcc会告诉你:

warning: ISO C90 forbids variable length array 'arr'

这意味着您的程序确实不符合c89 / c90。

更改-pedantic with -pedantic-errorsgcc将停止翻译。

这称为可变长度数组,允许在C99中使用。 使用-pedantic标志在c89模式下编译,编译器会给你警告

 [Warning] writing into constant object (argument 2) [-Wformat] [Warning] ISO C90 forbids variable length array 'arr' [-Wvla] [Warning] ISO C90 forbids mixed declarations and code [-pedantic]