2012-11-04 69 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) 
{ 
    ... 
} 
相關問題