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

发布于 2024-10-08 11:26:20 字数 874 浏览 0 评论 0原文

编辑:

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

#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 是我想要的列。

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

这就是我被告知解决问题的方法。

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 << 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

平安喜乐 2024-10-15 11:26:20

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

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;

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文