创建动态二维数组的其他方法?
编辑:
我已经完全修改了我的问题,因为我更好地了解了我想要做什么。
#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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当然有一个简单的方法,您需要分配一维数组,但将其用作二维数组:
Of course there is simple way, you need allocate one-dimensional array but use it as 2 dimensional: