我怎样才能声明这样一个数组:
int array[1000000];
作为静态数组、堆栈数组和堆分配数组?
最佳答案
您的任务似乎是在寻找这个:
// global variable; NOT on the stack. Exists in the data segment of the program
int globalvar[1000000];
void func()
{
// local stack-variable. allocated on the stack on function entry
// unavailable outside this function scope.
int stackvar[1000000];
// allocated on the heap. the only stack space used in the
// space occupied by the pointer variable.
int *heapvar = malloc(1000000 * sizeof(int));
if (heapvar != NULL)
{
// use heap var
// free heap var
free(heapvar)
}
}
或者也许是这样的:
void func()
{
// static variable; NOT on the stack. Exists in a program data segment (usually)
static int staticvar[1000000];
// local stack-variable. allocated on the stack on function entry
// unavailable outside this function scope.
int stackvar[1000000];
// allocated on the heap. the only stack space used in the
// space occupied by the pointer variable.
int *heapvar = malloc(1000000 * sizeof(int));
if (heapvar != NULL)
{
// use heap var
// free heap var
free(heapvar)
}
}
就其值(value)而言,除非您有一个 4 或 8 兆字节的保留调用堆栈(或更大),否则上面的函数可能会在输入时出错。对于如此大的尺寸,通常使用堆 (malloc()
/free()
)。但这似乎不是您的任务(目前)的内容。
关于c - 静态、堆栈和堆分配有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13419811/