Reputation: 229
I know array is allocated size in stack if it is local . How is memory allocated to following array in code . Also when I give negative input like -20 then answer is -80. It is used to give error in earlier compiler but not now. So how it is dealed now ?
int main()
{
int i;
scanf("%d",&i);
int a[i];
printf("%d",sizeof(a));
}
Upvotes: 1
Views: 505
Reputation: 206498
What you have is an Variable length array(VLA), which is allowed in C standard but not in C++.
Most C++ compilers provide support for it through compiler extensions though. C++ Standard provides an std::vector
which is usually used in C++ over VLA, since using VLA renders your code non-portable.
For an user program the elements of the VLA are located in contiguous memory locations just as in case of an normal array.Just the only difference is that the length of the array can be specified at run-time.
When you provide a negative size to the VLA, What you invoke is Undefined Behavior.
Reference:
C99 standard §6.7.5.2:
If the size is an expression that is not an integer constant expression... ...each time it is evaluated it shall have a value greater than zero.
Upvotes: 4