【发布时间】:2016-08-01 15:42:28
【问题描述】:
我有一个 void 函数
void foo(int *ptr) {
//trying to allocate memory to hold 5 ints
ptr = malloc(sizeof(int)*5):
//I loop ptr and assign each with a value i =0 to 4;
}
在主函数中我有这行
int main() {
int *num;
//I called the function
foo(&(num));
free(num);
return 1;
}
我得到 munmap_chunk() 无效指针错误。我确实试图挖掘更多信息,但我无法弄清楚这一点。我知道这对于从事 c 工作的人来说是基本的。我在想我是通过引用传递的,它应该可以工作,但事实并非如此。我是C新手,到目前为止一直很头疼。
【问题讨论】:
-
您传递给
foo()(int**) 的内容与foo()(int*) 期望的参数类型不匹配。没有从您的编译器收到任何警告消息?您可能打算使用void foo(int **ptr) { *ptr = malloc(...); ...} -
@P.P 如果你看主函数我传递了一个指针,一个指向 int 的地址
-
@user1986244 实际上,您传递了一个指针的地址。指向指针的指针。
foo()应该收到int **。