c++ - 静态内存中数组的大小可以在 C++ 运行时更改吗?怎么来的?

标签 c++ arrays dynamic-memory-allocation

<分区>

我已经从这里阅读了这一段:http://www.cplusplus.com/doc/tutorial/dynamic/

You could be wondering the difference between declaring a normal array and assigning dynamic memory to a pointer, as we have just done. The most important difference is that the size of an array has to be a constant value, which limits its size to what we decide at the moment of designing the program, before its execution, whereas the dynamic memory allocation allows us to assign memory during the execution of the program (runtime) using any variable or constant value as its size.

但是我的这段代码工作得很好:

int number;
cin>>number;
int myArray[number];

cout<<sizeof(myArray)/sizeof(myArray[0])<<endl;
cout<<sizeof(myArray)<<endl;

这是否意味着数组是在动态内存中创建的?或者它是在静态内存中创建的,但它的大小仍然在运行时确定?

最佳答案

正如我在评论中指出的,但这里有更多细节。

在标准 C++ 中,必须在编译时知道数组的大小。在您的示例中,情况并非如此。你的代码编译是因为你(大概)使用启用了 variable length array 扩展的 gcc。

正确设置警告级别将阻止此代码编译。

关于c++ - 静态内存中数组的大小可以在 C++ 运行时更改吗?怎么来的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13545489/

相关文章:

c++ - 有人知道 `cimg::exception_mode() = 0;` 是做什么的吗?

java - 有没有像数组一样工作的列表?

php - 在 PHP 和 Javascript 之间传输数组的最佳方法

c - 我如何使用结构?

c++ - sizeof 运算符的问题

c++ - 自定义容器上的C++ “periodic”迭代器

c++ - 先发生什么 - 堆栈展开或返回值的复制

javascript - 如何使用下划线根据 id 提取对象

fortran - 使用接口(interface)和可分配的 WORK 数组的 Lapack 例程 SGELS 中出现错误

c - 我需要帮助理解这行动态创建数组的代码吗?