c++ - 声明没有大小的数组数据成员

标签 c++ arrays

我想了解数组在 C++ 中的工作原理。一些关于 SO 的好线程,但我有一个问题我找不到答案是:

为什么可以声明没有大小的数组数据成员?我认为在 C++ 中数组大小必须是编译时常量?

例子:

#include<iostream>

class Object{

public:
      Object(std::size_t n){  

        for(std::size_t i = 0; i<n; ++i) { array[i] ='X'; }

        //prints 0 because 'sizeof' is compile-time operator
        std::cout << "compile-time size: " << sizeof(array) << std::endl;
        std::cout << "run-time size " << n << std::endl;
      }

private:
      char array[];
};  

int main( int argc, char** argv )
{
  Object obj(10);      //10 chars

  std::size_t n;
  std::cin >> n;
  Object obj2(n);      //n chars in automatic storage i.e. on the stack??
}

Input: 
  n = 1000
Output: 
  compile-time size: 0
  run-time size 10
  compile-time size: 0
  run-time size 1000

这是否意味着obj2的数组数据成员存储在自动存储中,但大小在运行时动态确定?

谢谢

最佳答案

Why is it possible to declare array data members with no size?

在标准 C++ 中,它不是。在 C 中,您可以将一个放在结构的末尾,以允许可变大小的数组 - 但您必须确保为您想要使用的任何大小分配足够的存储空间。一些 C++ 编译器可能允许将其作为非标准扩展。

Does this mean that obj2's array data member is stored in automatic storage, but the size is determined dynamically at runtime ?

不,这意味着数组没有任何存储空间,您正在覆盖堆栈的其他部分。这不是个好主意。

如果你想要一个动态数组,使用std::vector

关于c++ - 声明没有大小的数组数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26614439/

相关文章:

javascript - 一次显示一个结果,但有延迟

c++ - Netbeans C++ 项目上的 SFML 错误

c++ - 为什么 const 引用会延长右值的生命周期?

javascript - 使用 "*"运算符在输入内进行乘法

javascript - 如果数组位于使用 javascript/php 的数组内,则将数组转换为字符串

java - 从二维坐标数组创建一条路径供 AI 遵循

arrays - 如何使用 NSKeyedArchiver swift 将复杂的 Arrayobjects 保存到设备

c++ - 关于 float 舍入错误

c++ - boost crc 每次产生不同的输出

c++ - 如何在 Windows 中管理 googletest 中的断言