[英]Dynamic memory allocation in c without malloc
這是我的一個朋友編寫的C程序。 據我所知,數組必須在C99引入VLA之前在編譯時初始化,或者在運行時使用malloc
。
但是這里程序從用戶那里接受了const
值,並相應地初始化了數組。 即使使用gcc -std=c89
,它也可以正常工作,但對我來說似乎很不對勁。 都是依賴於編譯器的嗎?
#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;
}
將-pedantic
添加到您的編譯選項中(例如-Wall -std=c89 -pedantic
), gcc
會告訴您:
warning: ISO C90 forbids variable length array 'arr'
這意味着您的程序確實不符合c89 / c90。
用-pedantic
更改-pedantic-errors
和gcc
將停止翻譯。
這稱為可變長度數組,在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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.