lin*_*uxD 6 c variables memory-management local
由于局部变量也称为自动变量,并且在访问函数时应该在运行时分配内存.
int main(){
int a; // declaration
return 0;
}
int main(){
int a[]; // compilation error, array_size missing
return 0;
}
int main(){
int a[2]; // declaration, but can't work without array_size,
// so at compile time it is checked!
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,在C中声明中给出array_size是一个规则,还是在编译时为数组分配内存(仍然是本地变量)
它是如何工作的?
根据K&R的C编程,数组是一个变量.第161号.
声明局部变量时,它的大小在编译时是已知的,但在执行期间会发生内存分配.
所以在你的例子中,没有大小的数组显然是编译器的问题,因为它不知道要包含在汇编代码中的大小是多少.
如果您不知道数组的大小,则始终可以使用指针类型和malloc/ free或甚至alloca.前两个在堆上运行,alloca实际上使用堆栈.
值得注意的例外是静态变量.它们的存储已经在编译/链接时分配,并且不能在运行时更改.
例子:
int main(int argc, const char *argv[])
{
int a; // a is a sizeof(int) allocated on stack
}
int main(int argc, const char *argv[])
{
int a[2]; // a is a sizeof(int)*2 allocated on stack
}
int main(int argc, const char *argv[])
{
int *a; // a is a sizeof(int*) allocated on stack (pointer)
a = alloca(sizeof(int)*4); // a points to an area with size of 4 integers
// data is allocated on stack
}
int main(int argc, const char *argv[])
{
static int a; // a is allocated in data segment, keeps the value
}
Run Code Online (Sandbox Code Playgroud)
正如 sgar91 在注释中所述,在调用函数时会分配一个数组(例如您的示例中的数组),并且大小必须是确定的。如果需要动态数组,则必须在堆上分配内存。
int *values = malloc(sizeof(int) * array_count);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20131 次 |
| 最近记录: |