m****i 发帖数: 712 | 1 #include
int main()
{
int n;
scanf("%d",&n);
int a[n];
int i;
for(i=0;i
{
a[i] = i;
printf ("%d ",a[i]);
}
return 1;
}
This code work,
But the compiler only know how big the array on run-time....
how the compiler allocate the array on stack during compile time? |
I**********s 发帖数: 441 | 2 I didn't try your code. But you better use malloc, that's safer.
char * a = (char *) malloc(sizeof(char) * n);
if (NULL == a) {
puts("out of memory");
exit(0);
} |
c****e 发帖数: 1453 | 3 the compiler just implicitly calls the new and delete, it's an easy one-to-
one mapping. |
p***o 发帖数: 1252 | 4 new? delete? malloc? free?
If you have to say it's some function call, it's alloca,
which allocates memory on the stack instead of the heap.
【在 c****e 的大作中提到】 : the compiler just implicitly calls the new and delete, it's an easy one-to- : one mapping.
|
t*****g 发帖数: 1275 | 5 Dynamic array on stack is allocated using calculated size instead of 'pre-
calculated' or 'hard-coded' size; The allocation is not different than
moving the stack pointer though. The following assembly code may show you
how it works (solaris on x86)
...
leal -0x8(%ebp),%eax ; pipe scanf output to this address
...
call -0x23d ; call scanf
movl -0x8(%ebp),%eax ; obain variable 'n' and save it to %eax
...
subl %eax,%esp ; grow the stack pointer
【在 m****i 的大作中提到】 : #include : int main() : { : int n; : scanf("%d",&n); : int a[n]; : int i; : for(i=0;i: { : a[i] = i;
|
y*****a 发帖数: 171 | 6 give n a value of something like 8192 or greater, you will see how it crashs
. |