【发布时间】: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