Dynamic memory allocation in c without malloc

2019-07-19 02:33发布

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

2条回答
Ridiculous、
2楼-- · 2019-07-19 02:40

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.

查看更多
叼着烟拽天下
3楼-- · 2019-07-19 02:53

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]
查看更多
登录 后发表回答