C++ 当我试图删除指针时,我的程序崩溃
每当我试图删除一个指针时,我都会收到“windows错误噪音”,然后我的程序就会冻结,但从未正式崩溃C++ 当我试图删除指针时,我的程序崩溃,c++,pointers,delete-operator,C++,Pointers,Delete Operator,每当我试图删除一个指针时,我都会收到“windows错误噪音”,然后我的程序就会冻结,但从未正式崩溃 void addIngredient(char ** & ingredients, int & numOfIng) { char * str = nullptr; char **tempArr = new char*[numOfIng]; numOfIng++; //init tempArr to nullptr for (int i
void addIngredient(char ** & ingredients, int & numOfIng)
{
char * str = nullptr;
char **tempArr = new char*[numOfIng];
numOfIng++;
//init tempArr to nullptr
for (int i = 0; i < numOfIng; i++)
{
tempArr[i] = nullptr;
}
//set the new array to the old array
for (int i = 0; i < numOfIng - 1; i++)
{
tempArr[i] = new char;
tempArr[i] = ingredients[i];
}
delete [] ingredients;
//point the old array to the new one
ingredients = tempArr;
//add the new element to the end of the old array
cout << "What new ingredient would you like to add? ";
str = new char[25];
cin >> str;
ingredients[numOfIng - 1] = str;
delete str;
//method tought to us in class on how to clear array and what is being pointers within the array
for (int i = 0; i < numOfIng; ++i)
{
delete [] tempArr[i]; //Freezes here
}
delete [] tempArr;
}
void添加元素(字符**和成分、整数和整数)
{
char*str=nullptr;
字符**tempArr=新字符*[numOfIng];
numOfIng++;
//初始化临时到空ptr
for(int i=0;istr;
成分[numOfIng-1]=str;
删除str;
//方法在课堂上教给我们如何清除数组以及数组中的指针
对于(int i=0;i
我希望删除数组的元素,然后删除指向该数组的指针,但当我运行它时,会出现标准windows错误噪音,我的程序会冻结,直到我在控制台窗口中按住ctrl+c键。新的编码,所以请不要火焰我太厉害。不确定这是否重要,但我正在使用Visual Studio 2017并在x86中进行调试。您正在分配一个对象(
char
),然后忘记了新对象:
tempArr[i] = new char;
tempArr[i] = ingredients[i];
您要做的是设置数据:
tempArr[i] = new char;
*(tempArr[i]) = *(ingredients[i]);
这样新角色就不会丢失
您还有另一个问题,当您执行删除[]成分时代码>,您没有删除基础指针。然后稍后删除临时子阵列(delete[]tempArr[i]
),因此您应该做的是:
for (int i = 0; i < numOfIng; ++i)
{
delete ingredients[i]; // Note that I remove the [], as you have only new char, not new char[1]
}
for(int i=0;i
之后不会删除,因为新的成分正在使用这些“旧的”tempArr
也可以考虑使用向量或唯一的指针来表示你的情况。< /P>请提供。
成分如何分配?不使用指针如何?你可以对字符串使用std::string
,对动态数组使用std::vector
请问你的老师为什么他们不教你这样的东西:void addingredent(std::vector&components){std::string component;if(std::cin>>component)component.push_back(std::move(component));}
@AlgirdasPreidž抱歉,其初始化为:char**components=nullptr代码>@JasonAdam“其初始化为:char**components=nullptr;
”如果是这种情况,components[i]
是未定义的行为
我想知道tempArr[I]
是否是一个字符串而不是一个字符(同时考虑到成分通常是字符串)。如果是这样,那么OP可能需要类似于tempArr[i]=new char[strlen(components[i])+1];strcpy(tempArr[i],components[i])
但是代码整体上是混乱的,所以我不认为这是唯一的问题。@john确实有很多混乱,但是你的评论很有价值,让我意识到OP在使用数组之前删除了数组。@MatthieuBrucher我很抱歉,components[i]
和tempArr[i]
假定为字符串。然而,在实现了John关于字符串复制的建议之后,我尝试为(inti=0;I
实现,然而,这导致了我最初的问题,它崩溃了。我把它改为delete[]成分[I]代码>因为我更改tempArr[I]=新字符代码>至tempArr[i]=新字符[strlen(成分[i])+1]再次,我为没有在我的原始帖子中指定tempArr[i]
是字符串而道歉。@JasonAdam您必须转换成分[numoffing-1]=str我猜,代码>也是字符串副本。