开发者

Other ways for creating dynamic two-dimensional array?

Edit:

I've completely revised my question as I have a better idea of what I want to do.

#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开发者_C百科 << endl; 

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

    cout << *x << endl; 

    return 0; 

}

test is supposed to be my two-dimensional array.

*x is supposed to contain the address of test[i][j] (assume that I have the cin >> i and cin >> j in my code).

where i is the row and j is the column that I want.

But it doesn't seem to be giving me the correct address. Unless I'm silly and reading it wrong.

This is the way that I was told to do the problem.


Of course there is simple way, you need allocate one-dimensional array but use it as 2 dimensional:

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜