可变大小的二维数组C ++ 2017

时间:2019-08-29 02:21:37

标签: c++ multidimensional-array memory-management

我正在尝试创建一个二维动态分配的数组,每当用户想要在该数组中输入其他数字时,该列的大小就会增加。也就是说,将在堆上分配一个新地址,并将其返回到“ arr”。在我的示例中,行是恒定的。问题是我无法动态分配内存并将整数分配给数组中除第一行以外的任何其他行。

int allocate(int** &arr, char choice)
{
    int x = 1;
    int index = 0;
    int row = 0;
    int colCount = 0;
    do
    {
        *(arr + index) = (new int + index);
        arr[row][index] = x;
        //(arr[0]+index)= new int*[index]; this fundementally does not work, cant modify left value

        colCount++;
        cout << x << "'s address " << &arr[row][index] << " I have " << colCount
              << " columns " << endl;
        x++;
        index++;
        cout << "Select another number?" << endl;
        cin >> choice;
    } while (choice != 'n');

    return colCount;
}

int main()
{
    int rowCount = 3;
    int colCount = 0;
    int **arr = new int*[rowCount];
    char choice = 'n';

    colCount = allocate(arr, choice);

    for (int i = 0; i < colCount; i++)
    {
        delete[] arr[i];
    }
    delete[] arr;

    return 0;
}

我的问题是这里的代码行

*(arr + index) = (new int + index);

虽然确实可以打印出我在函数中分配的值和地址,但是当我尝试删除分配的内存时却出现堆损坏。此外,我不知道如何获取分配的数字< / p>

此外,如果我没记错的话,*(arr + index)仅给我第一列的指针!所以我什至不知道为什么这行得通!

2 个答案:

答案 0 :(得分:0)

您为什么不使用vector<vector<int>>?向量是一个动态数组。

答案 1 :(得分:0)

我不知道*(arr + index) = (new int + index);行应该做什么。

如果要分配整数大小为columnSize的数组,则将其写为:

int * column = new int[columnSize]

如果要将指针存储在arr的{​​{1}}位置,请写

index

我不确定您想写什么,您的代码对我来说很混乱。您为什么不使用arr[index] = new int[columnSize]?还是std::vector<int>