【发布时间】:2018-02-28 21:50:13
【问题描述】:
我的目标是动态分配二维数组,以便提示用户输入他们想要创建的矩阵数组的行和列的大小。在动态分配行和列的大小后,用户将输入他们想要的任何值。以下是我的 C++ 代码:
#include <iostream>
using namespace std;
int main()
{
int* x = NULL;
int* y = NULL;
int numbers, row, col;
cout << "Please input the size of your rows: " << endl;
std::cin >> row;
cout << "Please input the size of your columns: " << endl;
std::cin >> col;
x = new int[row];
y = new int[col];
cout << "Please input your array values: " << endl;
for (int i = 0; i<row; i++)
{
for (int j = 0; j<col; i++)
{
std::cin >> numbers;
x[i][j] = numbers;
}
}
cout << "The following is your matrix: " << endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j<col; j++)
{
std::cout << "[" << i << "][" <<j << "] = " << x[i][j] << std::endl;
}
}
delete[] x;
delete[] y;
system("pause");
return 0;
}
不幸的是,当我在 Visual Studios 上运行此代码时,它给了我编译错误。
【问题讨论】:
-
你想要
std::vector<std::vector<int>>。 -
x[ i ][ j ]? link
-
您创建了两个一维数组,然后尝试使用它们,就好像它们神奇地连接在一起一样。去掉代码的用户 I/O 部分,集中精力学习如何构造一个二维数组。
标签: c++ arrays memory multidimensional-array dynamic-allocation