【问题标题】:Why can't I use a variable to make an array? [duplicate]为什么我不能使用变量来创建数组? [复制]
【发布时间】:2016-03-08 06:56:03
【问题描述】:

我想按照以下可变大小制作数组。

int buff_size = width*height*3;
unsigned char buffer[buff_size];

但我收到如下错误消息:

mfc_test5Dlg.cpp(418): error C2057: expected constant expression

如何制作可变大小的数组?

【问题讨论】:

  • 除了你的错字,考虑到错误似乎不是主要问题,VLA 是 C99 功能而不是 C++ 功能some compiler support it as an extension 但不是 Visual Studio。
  • 您的问题同时被 c 和 c++ 标记。在 C++ 中,您根本无法做到这一点。如果你修复语法错误,你可以在 c 中做到这一点
  • 如果你想拥有一个动态大小的变量或数组,你可以使用“指针”和“内存分配”。进行一些搜索,您应该会找到示例。

标签: c++ arrays


【解决方案1】:

你有一个;。改变

int buff_size; = width*height*3;

int buff_size = width*height*3;

除此之外;如果你真的想要一个可变长度的数组;您必须动态分配它;您可以通过多种方式做到这一点:

C++:新建和删除:

unsigned char* buffer = new unsigned char[buff_size];
...
delete[] buffer;

C:malloc 和 free:

unsigned char* buffer = (unsigned char*) malloc(buff_size); // or malloc(sizeof(char) * buff_size)
...
free(buffer);

【讨论】:

  • 这可能会修复错误,但仍然使用非标准的可变长度数组离开 OP。他们应该使用vector 或`new up an array。
  • 考虑到错误expected constant expression 我不认为这是实际问题。
  • 你是对的;我将其添加到我的答案中
  • sizeof(char)永远产生除 1 之外的任何内容。没用。
  • 你是对的,但我喜欢保持将 sizeof 放在那里的习惯,以避免与其他类型出现错误......我会将你的评论添加到答案中。
【解决方案2】:

在 C++ 中不能有可变大小的数组。如果您绝对愿意,您可以动态分配它,但使用 std::vector 几乎总是更好,无论如何,这是动态方式:

int buff_size = width*height*3;
unsigned char* buffer = new char[buff_size];
...

delete[] buffer;

【讨论】:

    【解决方案3】:

    您需要避免使用原始指针的 newdelete

    std::size_t const buff_size = width*height*3u;
    

    1) 尽可能使用std::vector<char>

    std::vector<char> buffer{buff_size};
    

    2) 如果可用,请使用std::make_unique

    auto buffer = std::make_unique<char[]>(buff_size);
    

    3) 否则手动使用std::unique_ptr

    std::unique_ptr<char[]> buffer{new char[buff_size]};
    

    【讨论】:

      【解决方案4】:

      在现代/安全/惯用 C++ 中,您可以使用 vector 创建可变大小数组:

      std::vector<unsigned char> buffer(buff_size);
      

      所有其他选项都是不安全的(您要么泄漏内存,要么比必要的更容易越界访问)。

      【讨论】:

      • 您能解释一下为什么使用std::vector&lt;char&gt;::operator[]std::unique_ptr&lt;char[]&gt;::operator[] 相比,越界访问数据的可能性较小吗?实际上,其他选项的自动化程度较低,因此更有可能以错误的方式使用,但这并不意味着它们不安全。
      • 这些运算符是等价的(忽略一些实现在调试模式下在vector::operator[] 中进行边界检查的事实)。但是,请考虑执行边界检查的vector::at,应该优先于operator[]unique_ptr&lt;T[]&gt; 不提供此类功能。
      • 选择at 而不是operator[] 通常首先需要某种问题敏感性(所以你不能免费获得安全......它只是更便宜;))。毫无疑问,vector 更易于使用,我普遍认为应该始终首选并尽可能使用它。
      猜你喜欢
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 2010-12-01
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 2011-07-19
      相关资源
      最近更新 更多