【发布时间】:2010-07-01 22:42:45
【问题描述】:
我在下面的代码中出现了分段错误,但是在我将其更改为指向指针的指针后,它就可以了。谁能给我任何理由?
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 块毫无意义。
-
如果这是 C,那些 try 块是无效的。这实际上是 C++ 吗?如果是这样,标签需要更改。
-
@Pavel:是的,但没用 ;-)
-
@Pavel 很好,如果你想动态分配一个你会使用的指针数组
-
要么问题是关于 C,在这种情况下
try块是错误的,要么是关于 C++,在这种情况下它不应该使用malloc()。
标签: c++ memory-management malloc