在C ++中删除指针 [英] Delete pointer in c++
本文介绍了在C ++中删除指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨!我也有删除poiter的问题.
这是我的代码.
int main()
{
向量< int *>列表;
int * a;
for ( int i = 0 ; i< ; 10; i ++)
{
a = 新 int ();
* a = i;
list.push_back(a);
}
int * value = 新 int () ;
* value = 4 ;
list.push_back(值);
cout<< " << * value<< endl;
/* 删除指针,减去5 */
for ( int i = 0 ; i< ; list.size(); i ++)
{
如果(* list [i]< 5)
{
删除列表[i];
list [i] = NULL;
}
}
如果(值!= NULL)
cout<< " << * value<< endl;
其他
cout<< " << endl;
}
我认为value必须为NULL,但不是Null,因此删除后如何将其为NULL!
解决方案
在这些行之间:
int * value = 新 int (); * value = 4 ; list.push_back(值); cout<< " << * value<< endl;
这行:
if(value!=NULL)
您对名称为value
的变量完全不执行.您认为通过什么魔术可以将其设置为NULL?
//那么删除后如何将其设置为NULL?
请尝试进行小的修改:):
vector< int *&> list;
所有其他解决方案都是有效的,但是还需要注意的是,当您在分配的变量上调用delete时,指针不会自动变为NULL值.即使释放了变量,指针本身也将保留该值.如果要使指针变为NULL,则必须手动设置它.
int *value = new int; //allocate memory on the heap delete value; //value STILL contains a pointer, but it''s no longer valid value = NULL; //Now the pointer has been reset
Hi! I have same problem with delete poiter.
This''s my Code.
int main()
{
vector<int*> list;
int *a;
for(int i=0;i<10;i++)
{
a=new int();
*a=i;
list.push_back(a);
}
int *value=new int();
*value=4;
list.push_back(value);
cout<<"value : "<<*value<<endl;
/*Delete pointer less 5*/
for(int i=0;i<list.size();i++)
{
if(*list[i]<5)
{
delete list[i];
list[i]=NULL;
}
}
if(value!=NULL)
cout<<"value : "<<*value<<endl;
else
cout<<"It's NUll"<<endl;
}
I think value must NULL but It''s Not Null, so how do it NULL when it''s deleted!
解决方案
Between these lines:
int *value=new int(); *value=4; list.push_back(value); cout<<"value : "<<*value<<endl;
and this line:
if(value!=NULL)
You do absolutely nothing to the variable namedvalue
. By what magic do you think it will get set to NULL?
// so how do it NULL when it''s deleted ?
Please try the small modification :) :
vector<int*&> list;
All the other solutions are valid, but it''s also important to note that when you call delete on an allocated variable, the pointer will NOT automatically turn into a NULL value. The pointer itself will keep the value even if the variable is deallocated. If you want the pointer to become NULL, you have to manually set it.
int *value = new int; //allocate memory on the heap delete value; //value STILL contains a pointer, but it''s no longer valid value = NULL; //Now the pointer has been reset
这篇关于在C ++中删除指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文