C 中的动态数组没有 malloc?
我一直想知道如何摆脱这个问题:
int main(int argc, char **argv) {
printf("%p %s %d\n", &argv[1], argv[1], strlen(argv[1]));
char copy[strlen(argv[1]) + 1];
strcpy(copy, argv[1]);
printf("%p %s %d\n", ©, copy, strlen(copy));
return 0;
}
无论如何,字符数组copy
都会被分配,并且程序运行良好,打印出原始文件和副本。 Valgrind 没有抱怨任何事情。
我认为如果没有 malloc,动态 数组在 C 中是不可能的。我错了吗?
I've always wondered how I could get away with this:
int main(int argc, char **argv) {
printf("%p %s %d\n", &argv[1], argv[1], strlen(argv[1]));
char copy[strlen(argv[1]) + 1];
strcpy(copy, argv[1]);
printf("%p %s %d\n", ©, copy, strlen(copy));
return 0;
}
The char array copy
gets allocated anyway and the program runs fine, printing out the original and the copy. And Valgrind doesn’t complain about anything.
I thought dynamic arrays weren’t possible in C without malloc. Was I wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一项 C99 功能,可以由编译器在早期版本上实现 。
This is a C99 feature and could be implemented on prior versions by the compiler.
可变长度数组起源于 GCC 扩展 ,但它们也被 C99 采用。
它们仍然在堆栈上分配,因此使它们“巨大”被认为是不好的风格(并且有一天可能会破坏您)。
Variable-length arrays originated as a GCC extension, but they were also adopted by C99.
They are still being allocated on the stack, so making them "huge" is considered bad style (and will likely break on you someday).
甚至在 gcc 和 C99 提供的“可变长度数组”存在之前,就已经存在:
alloca()
——它允许动态分配堆栈(“自动”)内存。Even before the existence of "variable length arrays," courtesy gcc and C99, there was:
alloca()
-- which allows dynamic allocation of stack ("automatic") memory.“变长数组”是在C99中被添加到C语言中的。这在第 6.7.5.2 节“数组声明符”中进行了介绍:
"Variable length arrays" were added to the C language in C99. This is covered in §6.7.5.2 "Array declarators":