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?
- If no, why does the compiler not issue any warning or error?
- Where will this memory be allocated: Stack or heap?
- Why does ANSI C/GCC allow this?