gpt4 book ai didi

c++ - 程序在删除结构中的指针数组时崩溃

转载 作者:行者123 更新时间:2023-11-30 02:03:03 25 4
gpt4 key购买 nike

删除命令出现时崩溃。它应该用指向数组的指针创建一个结构,用随机数填充它们,然后释放内存。在删除命令之前工作正常,在删除命令中它因我们没有 for 循环或 bool 检查而崩溃。

int main() {

cout << "start" << endl;
//Creating Struct
struct
{
int* ptrarray[10];
bool boolarray[10];
} data;

//Initializing Random Generator
srand ( time(NULL) );
cout << "Initializing: ";

//Allocating Memory and generating random numbers with for loops

for (int i = 0; i < 10; i++)
{
int counter = 0; //Counts numbers set
cout << i << " "; //Counting arrays initialized
data.ptrarray[i] = new int [12582912]; // Memory Allocation

for (int j = 0; j < 12582912; j++)//Number Generating
{
*data.ptrarray[i] = rand() % 899 + 100;
data.ptrarray[i]++;
counter++;
}

//Checking for failed initializations and declaring if success
if (counter == 12582912)
{
data.boolarray[i] = true;
}
else
{
data.boolarray[i] = false;
}
}

cout << endl;

//This is where it always crashes.
for (int i=0; i<10; i++)
{
if (data.boolarray[i] == true)
delete[] data.ptrarray[i];
}
cout << endl;

return 0;
}

我使用的是 MS Visual Studio 2010。

最佳答案

罪魁祸首是这一行:

data.ptrarray[i]++;

您正在更改指针,然后在修改后的指针上使用 delete []。这是行不通的:您必须将 delete[] 与从 new[] 获得的完全相同的指针一起使用。

尝试

data.ptrarray[i][j] = rand() % 899 + 100;

相反,这样您就不必更改指针。

关于c++ - 程序在删除结构中的指针数组时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12503486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com