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

时间:2010-12-19 08:09:48

标签: 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; 

}

测试应该是我的二维数组。

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

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

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

这是我被告知要解决问题的方式。

1 个答案:

答案 0 :(得分:1)

当然有简单的方法,你需要分配一维数组但是把它用作二维:

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;