编辑:
我已经完全修改了我的问题,因为我对我想做什么有了更好的了解。
#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/