I recently tried this experiment in which instead of going for dynamic memory allocation for memory requirements of unknown size, I did a static allocation. When an array a[i]
was declared by me, I kept i
(size of the array) variable and dependent on the input that the user gives.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
void function(int );
int main(void)
{
int i;
printf("Enter:");
scanf("%d",&i);
function(i);
printf("i = %d\n",i);
getch();
return 0;
}
void function(int i)
{
char a[i];
char b[4];
strncpy(a,"hello",i);
strcpy(b,"world");
int j = 0;
char *c = a;
for( j = 0; j< 20; j++ )
printf("%c",*c++);
}
My questions are:
Is such an operation legal?
It's called a variable length array.
VLAs are legal in ANSI C99 and as an extension to some pre-C99 compilers. GCC supports it both as strict C99 and as an extension to non-C99 code. It's also legal in C++0x.
If no, why does the compiler not issue any warning or error?
With gcc:
$ gcc -std=c89 src/vla.c -Wall -ansi -pedantic
src/vla.c: In function ‘function’:, not dynamic array.
src/vla.c:17: warning: ISO C90 forbids variable length array ‘a’
src/vla.c:21: warning: ISO C90 forbids mixed declarations and code
The presence of 'conio.h' from MSDOS indicates you're probably using a Microsoft Visual C++ compiler, so don't worry about it. MS has worked to make their compiler more conformant to the C++0x standard, but makes no claims about how standard its C compiler mode is. You're asking why Spanish dialect words aren't in the French dictionary.
Where will this memory be allocated: Stack or heap?
It is an automatic object, so most C implementations will put in on the stack for efficiency reasons.
Why does ANSI C/GCC allow this
It is useful for creating temporary arrays of variable size at runtime whose lifetime doesn't extend beyond the function call.