2012-11-04 23 views
-3

void del函数无法将obj_slot中的类指针设置为NULL;当我想删除它时,指针甚至不能设置为NULL

class test_object { 
public: 
    char *name; 
    int id; 

}; 

int current_amount; 
test_object *obj_slot[512]; 

void add(test_object *obj) 
{ 
    if(current_amount < 512) 
    { 
    obj->id = current_amount; 
    obj_slot[current_amount] = obj; 
    current_amount ++; 
    } 
    else { 
    std::cout<<"max exceeded"; 
    } 

} 

void printList(char *status){ 

    printf("%s\n",status); 
    for(int i = 0 ; i < current_amount ; i ++) 
    { 
    printf("list object id %i; string is %s,pointer:%p\n",obj_slot[i]->id,obj_slot[i]->name,obj_slot[i]); 

    } 

} 
void del(test_object *obj) 
{ 

    printList("before:"); 

    if(!obj) 
    return; 

    printf("deleting %s id %i,pointer %p\n",obj->name,obj->id,obj); 

    for(int i = obj->id ; i < current_amount - 1 ; i ++) 
    { 

    obj_slot[i] = obj_slot[i + 1]; 

    } 

    delete obj; 
    obj = NULL; 
    current_amount--; 

    printList("after:"); 
} 

//这是测试程序:

int main(int argc, char **argv) { 
      std::cout << "Hello, world!" << std::endl; 
      for(int i = 0 ; i < 5; i ++) 
      { 
       test_object *test = new test_object(); 
       char a[500]; 
       sprintf(a,"random_test_%i",i); 
       test->name = (char *)malloc(strlen(a) + 1); 
       strcpy(test->name,a); 
       add(test); 
      } 
      test_object *test = new test_object(); 
      test->name = "random_test"; 
      add(test); 
      del(test); 
      printf("test pointer after delete is %p\n",test); 
      return 0; 
     } 

我已经成立,我想在德尔功能为NULL删除指针地址;但控制台输出仍然是这样的:

之前: 列表对象ID 0;字符串是random_test_0,指针:0x706010

list object id 1;字符串是random_test_1,指针:0x706050

list object id 2;字符串是random_test_2,指针:0x706090

list object id 3;字符串是random_test_3,指针:0x7060d0

list object id 4;字符串是random_test_4,指针:0x706110

list object id 5;字符串是random_test,指针:0x706150

删除random_test ID 5,指针0x706150

后: 列表对象ID 0;字符串是random_test_0,指针:0x706010

list object id 1;字符串是random_test_1,指针:0x706050

list object id 2;字符串是random_test_2,指针:0x706090

list object id 3;字符串是random_test_3,指针:0x7060d0

list object id 4;字符串是random_test_4,指针:0x706110

测试指针删除后是0x706150

*正常退出*

+1

这是因为你是浪费你的生活与原指针,而不是使用适当的标准类。 – Puppy

+1

我想知道是否会更仔细地阅读C++教程(或至少谷歌的问题)伤害。 – 2012-11-04 12:14:43

+0

你不应该把'malloc'和'new'混合在一起。 –

回答

3

这是因为在del函数变量obj本地变量,所有的变化在该功能之外它将不可见。如果你想修改它,你应该通过它作为参考,而不是:

void del(test_object *&obj) 
{ 
    ... 
} 
相关问题