一个局部变量的C ++动态内存分配(C++ dynamic memory allocation of a local variable)

编程入门 行业动态 更新时间:2024-10-18 14:17:29
一个局部变量的C ++动态内存分配(C++ dynamic memory allocation of a local variable)

我在学校有一个计算机科学课,我们的老师正在讨论动态内存分配及其原因

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 error

this 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) :)

更多推荐

本文发布于:2023-07-26 00:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1268385.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   局部   分配   内存   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!