【问题标题】:Variable sized two dimensional array c++ 2017可变大小的二维数组 C++ 2017
【发布时间】:2019-08-29 02:21:37
【问题描述】:

我正在尝试创建一个二维动态分配的数组,每次用户想要在数组中输入一个额外的数字时,它的列大小都会增加。也就是说,将在堆上分配一个新地址并返回到“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);

虽然它确实打印出我在函数中分配的值和地址,但当我尝试删除分配的内存时出现堆损坏。另外,我不知道如何获取要分配的数字

另外,如果我没记错的话*(arr + index) 只给我第一列的指针!所以我什至不确定为什么会这样!

【问题讨论】:

  • 我觉得我的标题有点不清楚。启发我的是这篇帖子stackoverflow.com/questions/936687/… 我想用new 在堆上分配内存。他们的示例之间唯一不同的是 this ' int** a = new int*[rowCount]; 'for(int i = 0; i

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


【解决方案1】:

为什么不使用vector&lt;vector&lt;int&gt;&gt;? Vector是一个动态数组。

【讨论】:

    【解决方案2】:

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

    如果你想分配整数数组columnSize,你可以这样写:

    int * column = new int[columnSize]

    如果你想将指针存储在arr 的位置index 然后写

    arr[index] = new int[columnSize]

    我不确定你想写什么,你的代码让我很困惑。为什么不使用std::vector&lt;int&gt;?还是std::vector&lt;std::vector&lt;int&gt; &gt;

    【讨论】:

    • (new int + index) 是给我一个指向单个整数的指针,然后将指针 index 推进它之后的整数。一个近乎完美的未定义行为生成器。
    • 我认为我对 new 所做的是将指向堆上内存的指针返回给 arr。下次运行时,它会增加 1 到相邻的内存位置。看起来这就是我打印地址时发生的事情......
    猜你喜欢
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 2012-03-12
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    相关资源
    最近更新 更多