【问题标题】:Working with multi-dimensional arrays [closed]使用多维数组 [关闭]
【发布时间】:2013-02-25 11:24:18
【问题描述】:

我正在尝试构建一个适用于宽度矩阵的类。在它的构造函数中,它想知道数组的高度和宽度,并且它想要数组本身,然后它必须能够打印数组并重载一些运算符。 Array 必须是浮点数组。这是我到目前为止所拥有的: 两个定义的参数:

#define HEIGHT 3
#define WIDTH 3

制作数组:

void Assignment_1::start(){
    float **matrix = new float *[HEIGHT];
    for (int i = 0; i < HEIGHT; i++){
        matrix[i] = new float[WIDTH];
    }
    //  5   6   11
    //  7   2   8
    //  5   1   4
    matrix[0][0]=5;
    matrix[0][1]=6;
    matrix[0][2]=11;
    matrix[1][0]=7;
    matrix[1][1]=2;
    matrix[1][2]=8;
    matrix[2][0]=5;
    matrix[2][1]=1;
    matrix[2][2]=4;
    Matrix * matrixA = new Matrix(HEIGHT,WIDTH,matrix);
    matrixA->printMatrix();
}

现在我知道一个 C++ 二维数组存在一个普通的 HEIGHT 指针数组,每个指针都指向一个 WIDTH 大小的数组。

构造函数和全局变量:

Matrix::Matrix(int width, int height, float **array){
    this->height = height;
    this->width = width;
    this->array = array;
}
//in Matrix.h:
int width, height;
float ** array;

到目前为止,一切都很好。现在我想通过打印来实际使用数组:

void Matrix::printMatrix(){
    for (int h = 0; h < height; h++){
        for (int w = 0; w < width;w++){
            std::cout <<array[height][width]<<"    ";
        }
        std::cout << std::endl;
    }
}

这就是问题所在:程序简单地崩溃了。我有点明白它为什么会崩溃:我想我需要得到 array[h] 指向的内容(这是一个大小宽度的浮点数组),但尝试这样做会给我错误:无法将 float* 转换为 float[] *。我需要做什么?

【问题讨论】:

  • 数组[高度][宽度] -> 数组[h][w]。此外,std::vector。此外,boost.multiarray。还有gist.github.com/rmartinho/3959961
  • 哦。输入错误。完全了解多维数组后,我会研究向量,但我还在学习,所以在我了解基础知识之前,我不想急于模板。
  • std::vector 的基础。手动内存管理是高级的东西。

标签: c++ pointers multidimensional-array


【解决方案1】:

The robot already answered your question:

for (int h = 0; h < height; h++){
    for (int w = 0; w < width;w++){
        std::cout <<array[height][width]<<"    ";
                  //      ^^^^^^  ^^^^^
    }
    std::cout << std::endl;
}

您正在访问哪些条目?好吧,总是array[height][width]。但是,array 仅包含 height 元素,因此这种访问会导致未定义的行为。只需应用您的循环变量hw

for (int h = 0; h < height; h++){
    for (int w = 0; w < width;w++){
        std::cout << array[h][w]<<"    ";
    }
    std::cout << std::endl;
}

但是,这仍然远非最佳。你应该使用更容易使用的类型,例如std::vector:

typedef std::vector<float> float_vector;
typedef std::vector<float_vector> float_matrix;
float_matrix matrix(HEIGHT,float_vector(WIDTH));

std::vector 是最重要的类型之一。掌握它。

【讨论】:

    【解决方案2】:

    这是因为二维数组和指向指针的指针不同。可以试试吗

    float **array to float (*array)[size]?

    将array[height][width]改为array[h][w]

    【讨论】:

      【解决方案3】:
      void Matrix::printMatrix(){
          for (int h = 0; h < height; h++){
              for (int w = 0; w < width;w++){
                  std::cout <<array[h][w]<<"    ";
              }
              std::cout << std::endl;
          }
      }
      

      不是高度和宽度——它是数组的大小,使用迭代器 h,w

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-05
        相关资源
        最近更新 更多