动态分配输入,并在C ++中输出2-D数组

问题描述 投票:2回答:2

我的目标是动态分配2维数组,以便提示用户输入他们想要创建的矩阵数组的行和列的大小。在动态分配行和列的大小之后,用户将输入他们希望的任何值。以下是我的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上运行此代码时,它给了我编译错误。

c++ arrays memory multidimensional-array dynamic-allocation
2个回答
4
投票

以下是如何使用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;
}

1
投票

我解决了它:

#include <iostream>
//#include <vector>

using namespace std;

int main() {
int row, col;
cout << "Please enter the rows size: " << endl;
cin >> row;
cout << "Please enter the column size: " << endl;
cin >> col;

cout << "Please enter the numbers you want to put into a 2D array (it should 
look like a matrix graph)." << endl;
cout << "Press enter after each number you input: " << endl;

int** map = new int*[row];
for (int i = 0; i < row; ++i)
    map[i] = new int[col];

for (int i = 0; i < row; i++) {
    for (int j = 0; j < col; j++) {
        cin >> map[i][j];
    }

}

cout << endl;
//Print
for (int i = 0; i < row; i++) {
    for (int j = 0; j < col; j++) {
        cout << map[i][j] << " ";
    }
    cout << endl;

}
cout << endl;


// DON'T FORGET TO FREE
for (int i = 0; i < row; ++i) {
    delete[] map[i];
}
delete[] map;
system("pause");
return 0;
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.