2012-08-30 159 views
2

我想在函數中分配內存,我不知道我在做什麼錯。 我想這一點:在函數中初始化,並沒有在主要初始化

int main() 
{ 
    int* test= 0; 
    initialize(test, 10); 
    int test2 = test[2]; 
    delete[] test; 
} 

void initialize(int* test, int count) 
{ 
    test = new int[count]; 
    for (int i = 0; i < count; i++) 
    { 
     test[i] = i; 
    } 
} 

但我收到此錯誤:未處理的異常在0x770d15de魯棒Simulation.exe:0000005:訪問衝突讀取位置0x00000008。 斷行:int test2 = test [2];

但這個工程:

int main() 
{ 
    int* test=0; 
    test = new int[10]; 
    for (int i = 0; i < 10; i++) 
    { 
     test[i] = i; 
    } 

    int test2 = test[2]; 
    delete[] test; 
} 

有一個範圍的問題嗎?我想,因爲我傳遞了它將被分配的指針,我可以在初始化函數之外訪問它。

感謝您的幫助

+1

降'new'和'delete',使用'VECTOR'。問題已修復。 –

+0

這對教育目的很有好處,但在真實情況下你應該避免這樣的代碼。 – juanchopanza

回答

2

做以下變化: -

initialize(&test, 10); 
.... 


void initialize(int** test, int count) 
{ 
    *test = new int[count]; 
    for (int i = 0; i < count; i++) 
    {   (*test)[i] = i;  } 
} 

C++呼籲引用如果你想另一個特點,因爲它是: -

void initialize(int*& test, int count) 
{ 
     test = new int[count]; 
     for (int i = 0; i < count; i++) 
     {   test[i] = i;  } 
} 

你正在做的是通過測試[從主](地址將通過)並存儲在另一個本地指針變量名爲test.This新變量e具有函數範圍的生命期並且很快被刪除,在函數完成後留下垃圾。

另一種選擇是

int* test= initialize(test, 10); 

和變化初始化爲

int* initialize(int* test, int count) 
    { 
      test = new int[count]; 
      for (int i = 0; i < count; i++) 
      {   test[i] = i;  } 
      return test; 
    } 
2

指針也通過值傳遞。您需要:

void initialize(int*& test, int count) 

您的版本不改變原來的指針:

void initialize(int* test, int count) 
{ 
    //test is a copy of the pointer because it was passed by value 
    //... 
} 

在此之後,很明顯,爲什麼delete[]失敗 - 因爲在main原來的指針永遠不會初始化。

+0

更不用說當'test'仍然爲0時'test [2]'。這就是爲什麼它有讀取0x00000008的問題,這是OP的兩個int寬度超過0。 – chris

1

您需要將指針的引用傳遞到initialise函數中。原型改爲

void initialize(int* &test, int count) 

new返回值被分配給按值傳遞時被創建的指針是副本。因此,當函數退出時,該地址會隨着副本超出範圍而丟失,因此您有內存泄漏。因此你的test指針永遠不會指向任何分配的內存,因此刪除它會給你一個訪問衝突。

按引用傳遞允許test指針被函數修改