gpt4 book ai didi

c - 为什么不能在堆栈上分配动态大小的数组?

转载 作者:太空狗 更新时间:2023-10-29 16:07:29 25 4
gpt4 key购买 nike

在 C 中,我们都知道:

int i[500]; // Array of 500 integers on stack
int *i = malloc(sizeof(int) * 500); // Array of 500 integers on heap

堆栈大小随着函数从中压入和弹出变量而增长和缩小。但为什么不能从堆栈中压入和弹出一个动态大小的数组?

最佳答案

是的,他们可以:

http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits. For example:

 FILE *
concat_fopen (char *s1, char *s2, char *mode)
{
char str[strlen (s1) + strlen (s2) + 1];
strcpy (str, s1);
strcat (str, s2);
return fopen (str, mode);
}

简单测试:

$ cat testarray.c 
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
size_t n = atol(argv[1]), i;
printf("array size: %lu\n", n);

int a[n];

for (i=0; i<n; ++i) {
a[i] = i;
}

printf("%d\n", a[0]);

return 0;
}

$ ./a.out 100000
array size: 100000
0
$ ./a.out 1000000
array size: 1000000
0
$ ./a.out 10000000
array size: 10000000
Segmentation fault
$ ./a.out 100000000
array size: 100000000
Segmentation fault

关于c - 为什么不能在堆栈上分配动态大小的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23128407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com