我在下面的代碼中存在分段錯誤,但是在將其更改爲指針指針後,它很好。有人能給我任何理由嗎?爲什麼需要指針指針來分配內存中的功能
void memory(int * p, int size) {
try {
p = (int *) malloc(size*sizeof(int));
} catch(exception& e) {
cout<<e.what()<<endl;
}
}
它不會在主函數工作作爲打擊
int *p = 0;
memory(p, 10);
for(int i = 0 ; i < 10; i++)
p[i] = i;
但是,它的工作原理是這樣的。
void memory(int ** p, int size) { `//pointer to pointer`
try{
*p = (int *) malloc(size*sizeof(int));
} catch(exception& e) {
cout<<e.what()<<endl;
}
}
int main()
{
int *p = 0;
memory(&p, 10); //get the address of the pointer
for(int i = 0 ; i < 10; i++)
p[i] = i;
for(int i = 0 ; i < 10; i++)
cout<<*(p+i)<<" ";
return 0;
}
由於malloc永遠不會拋出,所以這些try塊沒有意義。 – 2010-04-12 22:27:45
如果這是C,那些try塊是無效的。這實際上是C++嗎?如果是這樣,標籤需要改變。 – 2010-04-12 22:31:22
@Fred,這個問題與C也有關係,即使片段是C++,正如你所指出的那樣。我添加了C++標記 – hhafez 2010-04-12 22:39:12