我在学校有一个计算机科学课,我们的老师正在讨论动态内存分配及其原因
cin>>size; int array[size]; // According to him this should result in a compiler error这不应该工作,而是我们应该使用:
int *p, size; cin>>size; p = new int[size] ... delete[] p;我的问题是,为什么第一个例子工作,如果你不能像这样动态地声明数组?
更新:所有测试都在GNU GCC Compliler中完成 ,上面的代码位于主函数内部
I had a computer science class at school and our teacher was talking about dynamic memory allocation and why
cin>>size; int array[size]; // According to him this should result in a compiler errorthis shouldn't work and instead we were supposed to use:
int *p, size; cin>>size; p = new int[size] ... delete[] p;My question is, why does the first example work if you cannot declare dynamically arrays like that?
UPDATE: All tests are made in GNU GCC Compliler and the code above is inside the main function
最满意答案
您正在使用支持可变长度数组的非标准编译器。 你的教授是对的, int array[size]不应该编译。
你的教授也是 错误 告诉你使用p = new int[size] 。 他应该做的是告诉你使用std::vector<int> p(size) 。 (好吧,出于教育目的,这没关系):)
You're using a non-standard compiler, that supports variable length arrays. Your professor is right, int array[size] shouldn't compile.
Your professor is also wrong telling you to use p = new int[size]. What he should do is tell you to use std::vector<int> p(size). (okay, for educational purposes this is OK) :)
更多推荐
发布评论