c++ - 创建动态二维数组的其他方法?

标签 c++ pointers multidimensional-array

编辑:

我已经完全修改了我的问题,因为我对我想做什么有了更好的了解。

#include <iostream>
#include <cstdlib>
using namespace std; 

int main(){
    const int max_rows = 10; 
    const int max_cols = 10; 

    int *test = new int[max_rows * max_cols]; 

    for(int i = 0; i < 100; i++){
        test[i] = 1 + (rand() % 100);  
    }

    for(int i = 0; i < 100; i++){
        cout << "#" << i << " " << test[i] << endl; 
    }

    int *b = &test[0]; 

    cout << *b << endl; 

    int *x = b + (i * sizeof(int) * max_cols) + (sizeof(int) * j); 

    cout << *x << endl; 

    return 0; 

}

test 应该是我的二维数组。

*x 应该包含 test[i][j] 的地址 (假设我的代码中有 cin >> i 和 cin >> j)。

其中 i 是行,j 是我想要的列。

但它似乎没有给我正确的地址。除非我很傻并且读错了。

这就是我被告知做题的方式。

最佳答案

当然有一个简单的方法,你需要分配一维数组并将其用作二维:

const int row = 5;
const int col = 7;
int *twoD  = new int[row * col];
std::cout << twoD [4*row + 3]; //sample to access [3][4]
return 0;

关于c++ - 创建动态二维数组的其他方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4482106/

相关文章:

c++ - 带有图形的 UI 蒙皮

c++ - 智能指针模板和自动删除指针

C++::Pointers - 从基类到派生类的转换

c - C语言中如何获取指向指针的指针?

delphi - 从指针复制数据?

python - "expand"numpy ndarray 的好方法?

将指针转换为二维数组

c++ - 使用数组乘以矩阵?

c++ - 在命名空间中包含实现文件以避免名称冲突

C++ 私有(private)变量名和继承歧义