Dynamic memory allocation in c without malloc

时光毁灭记忆、已成空白 提交于 2019-12-11 03:56:40

问题


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

回答1:


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.




回答2:


This called Variable Length Arrays and allowed in C99 . Compiling in c89 mode with -pedantic flag, compiler will give you warnings

[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]


来源:https://stackoverflow.com/questions/19208834/dynamic-memory-allocation-in-c-without-malloc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!