用C动态数组没有malloc的? [英] Dynamic arrays in C without malloc?
问题描述
我一直在想,我怎么能逃脱这样的:
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;
}
该字符数组复制
被分配无论如何,程序运行正常,打印出的原件和复印件。而Valgrind的不抱怨什么。
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.
我想的动态的阵列是不可能在C时不malloc的。难道我错了吗?
I thought dynamic arrays weren’t possible in C without malloc. Was I wrong?
推荐答案
这是C99的功能,并且可以在的以前版本的编译器。
This is a C99 feature and could be implemented on prior versions by the compiler.
变长自动数组被允许在ISO C99,并作为
扩展GCC接受他们C90模式和C ++。这些阵列
宣布像任何其他自动数组,但具有的长度是
不是一个常数前pression。存储在点分配
声明和解除当护具级退出。
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 brace-level is exited.
这篇关于用C动态数组没有malloc的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!