Code:
#include <stdio.h>
int main() {
int size;
scanf("%d", &size);
int foo[size];
for(int i = 0; i < size; i++)
scanf("%d", &foo[i]);
for(int i = 0; i < size; i++)
printf("%d\n",foo[i]);
return 0;
}
How does this code compile? More specifically: how does the compiler know what is the size of frame main
if size of local variable foo
is not known at compile time. I was expecting a compile error along the lines: "foo
has incomplete type"
这段代码是如何编译的?更具体地说:如果在编译时不知道局部变量foo的大小,编译器如何知道frame main的大小是多少。我一直在期待编译错误:“foo有不完整的类型”
To have also tried the code and it also runs fine:
要尝试代码,它运行良好:
1 个解决方案
#1
3
In your code, you will first read data to specify size of array elements and then it will allocate that array on stack.
在您的代码中,您将首先读取数据以指定数组元素的大小,然后它将在堆栈上分配该数组。
This approach is available from C99.
这种方法可从C99获得。
How compiler knows the size? It doesn't know. if you will enter too big value for size
you may get stack overflow.
编译器如何知道大小?它不知道。如果您输入的值太大,可能会出现堆栈溢出。
It will compile in a way that it will make sure to create as big push as required to put entire array to stack according to variable of size multiplied by size of single array element:
它将以一种方式编译,它将确保根据大小的变量乘以单个数组元素的大小将整个数组放入堆栈所需的大量推送:
stack_size_usage = size * sizeof (int)
In C89, this would reproduce error as all variables must be first initialized before any code can be executed.
在C89中,这将重现错误,因为必须首先初始化所有变量,然后才能执行任何代码。
I would instead use HEAP memory for this type of allocation.
我会改为使用HEAP内存进行此类分配。
#include <stdio.h>
int main() {
int size;
int* foo;
scanf("%d", &size);
foo = malloc(sizeof(*foo) * size);
if (!foo) { /* failed, stop program */ }
for(int i = 0; i < size; i++)
scanf("%d", &foo[i]);
for(int i = 0; i < size; i++)
printf("%d\n",foo[i]);
free(foo);
return 0;
}
#1
3
In your code, you will first read data to specify size of array elements and then it will allocate that array on stack.
在您的代码中,您将首先读取数据以指定数组元素的大小,然后它将在堆栈上分配该数组。
This approach is available from C99.
这种方法可从C99获得。
How compiler knows the size? It doesn't know. if you will enter too big value for size
you may get stack overflow.
编译器如何知道大小?它不知道。如果您输入的值太大,可能会出现堆栈溢出。
It will compile in a way that it will make sure to create as big push as required to put entire array to stack according to variable of size multiplied by size of single array element:
它将以一种方式编译,它将确保根据大小的变量乘以单个数组元素的大小将整个数组放入堆栈所需的大量推送:
stack_size_usage = size * sizeof (int)
In C89, this would reproduce error as all variables must be first initialized before any code can be executed.
在C89中,这将重现错误,因为必须首先初始化所有变量,然后才能执行任何代码。
I would instead use HEAP memory for this type of allocation.
我会改为使用HEAP内存进行此类分配。
#include <stdio.h>
int main() {
int size;
int* foo;
scanf("%d", &size);
foo = malloc(sizeof(*foo) * size);
if (!foo) { /* failed, stop program */ }
for(int i = 0; i < size; i++)
scanf("%d", &foo[i]);
for(int i = 0; i < size; i++)
printf("%d\n",foo[i]);
free(foo);
return 0;
}