jac*_*ack 2 c++ memory arrays multidimensional-array dynamic-allocation
我的目标是动态分配二维数组,以便它提示用户输入他们要创建的矩阵数组的行和列的大小。在动态分配行和列的大小之后,用户将输入所需的值。以下是我的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;
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,当我在Visual Studios上运行此代码时,它给了我编译错误。
这是使用c ++ 11 new和delete运算符动态分配2D数组(10行20列)的方法
码:
int main()
{
//Creation
int** a = new int*[10]; // Rows
for (int i = 0; i < 10; i++)
{
a[i] = new int[20]; // Columns
}
//Now you can access the 2D array 'a' like this a[x][y]
//Destruction
for (int i = 0; i < 10; i++)
{
delete[] a[i]; // Delete columns
}
delete[] a; // Delete Rows
return 0;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3227 次 |
最近记录: |