c++ 如何在每次用户要求时添加新行?

afdcj2ne  于 2022-12-15  发布在  其他
关注(0)|答案(1)|浏览(135)

我的任务是创建一个函数,每当用户要求时,它就会向2d Array添加一行。为了简单起见,我有一个默认的行值和一个应该保留的列值。这个任务可以引用一个书架。一旦有了一定数量的书或书架的该行,就移动到下一行,开始在那里放置书。
另外,一旦创建了一个新行,我应该如何释放程序?我是一个新的程序员,如果我的问题听起来很愚蠢,我道歉。提前感谢!
附件是我目前掌握的资料。

#include <iostream>
#include <string>
using namespace std;
int **addRows(int row, int cols, int values)
{
    // Declare a 2d Array
    int **twoD;
    twoD = new int *[row];
    // Fill each row with a column
    for (int i = 0; i < row; i++)
    {
        twoD[i] = new int[cols];
    }
    // Fill each row, column with value
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            twoD[i][j] = values;
        }
    }

    // Return the 2d array
    return twoD;
}

int main()
{
    int **twoD;
    int row = 1;
    int cols = 5;
    int values = 1;
    int userInput;

    // Call the function with 3 parameters by assigning the returned array to twoD
    twoD = addRows(row, cols, values);
    cout << "Do you want to add a row? 1 for yes, 0 for no, -1 to exit";
    cin >> userInput;

    while (userInput != -1)
    {
        if (userInput == 1)
        {
            twoD = addRows(row, cols, values);
        }
        else
        {
            // Print out each value in the 2d Array to console
            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < cols; j++)
                {
                    cout << twoD[i][j];
                }
                cout << endl;
            }
            // Free the memory
            for (int i = 0; i < row; i++)
            {
                delete (twoD[i]);
            }

            delete (twoD);
        }
        cout << "Do you want to add a row? 1 for yes, 0 for no, -1 to exit";
        cin >> userInput;
    }
}
gdrx4gfi

gdrx4gfi1#

您的代码缺少以下行:

//remove memory allocation of array of columns for each row
    for (int i = 0; i < row; i++) {
        delete[] twoD[i];
    }
    //remove memory allocation of array of rows
    delete[] twoD;
    //increase the amount of rows in our new twoD matrix
    row++;

在本节中:

if (userInput == 1)
    {
        //right here
        twoD = addRows(row, cols, values); //call addRows to generate the new twoD matrix with the increased row count
    }

相关问题