【问题标题】:Create an array dynamically in C++在 C++ 中动态创建数组
【发布时间】:2016-11-09 11:27:32
【问题描述】:

我必须创建一个矩阵,其宽度和高度由从写入文件中获得的两个参数确定。但是,在某些情况下,当矩阵太大时,我有一个segmentation fault。我认为可能是因为我正在以静态方式创建矩阵,所以我需要动态创建它,但是这里出现了我的问题,因为我不知道该怎么做。 我现在的代码是这样的:

    FILE * fp;
    unsigned int width=0;
    unsigned int height=0;
  //Open the file. argv[4] parameter contains the file
  fp=fopen (argv[4],"r"); 
  //Go to the last position which indicates the size
    fseek(fp, 0, SEEK_END); 
  //Return to the start:
    rewind(fp);
  //The value of the first 4 bytes represent the width
    size_t return1 = fread(&width,4,1,fp);
  //The value of the next 4 bytes represent the height
    size_t return2 = fread(&height,4,1,fp);
 //Matrix creation
   if (return1 > 0 && return2 > 0) {
     unsigned int matrix[width][height];

【问题讨论】:

  • 您是如何设法发布带有heigth 错字的代码的?不管怎样,开始吧: 1. 用 C++ 做事,就像用 C++ 做的一样 2. 使用 Google
  • @LogicStuff 已编辑。抱歉,输入有误

标签: c++ c++11 matrix segmentation-fault malloc


【解决方案1】:

如果您不知道如何动态创建数组,我绝对建议您改用 vector 类。

向量是动态分配的,并且可以缩放。

std::vector<unsigned int> matrix{width * height};

请注意,我将向量设为单维,因为它在分配向量时确实简化了很多。

要访问您可以使用的特定坐标:

matrix.at(w * width + h);

其中wh 是坐标,h 显然应该在0 &lt;= h &lt; height 范围内。

如果你要动态分配你的数组,你必须使用new 操作符,然后必须记得使用正确的delete[] 操作符进行清理。在 Stack Overflow 上有一个更好的答案:How do I declare a 2d array in C++ using new?

基本上可以归结为:

unsigned int** matrix = new unsigned int*[width];
for (int w = 0; w < width; ++w) {
    matrix[w] = new unsigned int[height];
}

然后你必须记住再次删除矩阵,使用类似这样的东西:

for (int w = 0; w < width; ++w) {
    delete [] matrix[w];
}
delete [] matrix;

因此,换句话说,我建议您改用vector 类。

当然,对于足够大的宽度和高度值,即使vector 也会失败,这仅仅是因为您试图分配太多内存。如果是这种情况,我认为你应该重新审视你的设计,并重新考虑它是如何制作的。

记得在使用向量时包含vector 标头:

#include <vector>

【讨论】:

  • 使用向量并编译它,我得到这个错误:terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check: __n (which is 1) &gt;= this-&gt;size() (which is 1)
  • @giorgioW 你对函数at 的输入是什么?
  • 执行错误,抱歉。输入是一个向量,width*height 的大小称为matrixRed,像这样:matrixRed.at(i*width+j)=intr;
  • @giorgioW - 请注意,索引从 0 开始,因此如果 this-&gt;size() == 1 唯一可能的索引是 0 - 在您的情况下意味着 i == 0j == 0
【解决方案2】:
unsigned int matrix[width][height];

这有两个问题。

首先,widthheight 不是编译时常量,这是 C++ 标准对数组大小的要求。因此,您的程序格式错误。您的编译器可能支持可变长度数组 (VLA) 作为语言扩展,因此无论如何它都可以与您的编译器一起使用。

其次,VLA 可能存储在堆栈上,堆栈空间有限。事实上,使用大数组,您可以轻松地溢出堆栈。你是对的,你需要动态分配数组。既是因为大小是动态的(假设您希望您的程序与不支持 VLA 的其他符合标准的编译器一起使用),而且因为它可以防止堆栈溢出。

创建动态数组的最简单方法是std::vector。 Tommy Andersen 在他的回答中更深入地介绍了如何使用向量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 2021-06-26
    • 2013-12-16
    • 2011-06-09
    • 2020-05-20
    • 2018-05-19
    • 1970-01-01
    相关资源
    最近更新 更多