嘿,我正在尝试将指针内存分配 d =(deque*)malloc(sizeof(deque));
移动到名为 void initDeque()
的第一个函数中。我尝试在 main
中保留声明并在函数中分配内存,但程序在初始化双端队列后崩溃,我无法在其他函数中使用指针。
代码如下:
int main(){
int x;
deque *d;
d = (deque*)malloc(sizeof(deque));
initDeque(d);
putFront(d,10);
以及我想为指针移动内存分配的函数:
void initDeque(deque *d){ //Create new deque
//d = (deque*)malloc(sizeof(deque));
printf("Initializing deque\n");
d->front=NULL;
d->rear=NULL;
}
如果声明和分配在 main()
中,程序运行良好,但当我将分配放入 void initDeque
时程序崩溃。
最佳答案
参数(甚至指针)是 passed by value在 C 中。
所以返回指针:
deque *make_queue(){ //Create new deque
deque *d = malloc(sizeof(deque));
if (!d) { perror("malloc"); exit(EXIT_FAILURE); };
printf("Initializing deque\n");
d->front=NULL;
d->rear=NULL;
return d;
}
并在 main
的开头调用 d = make_queue();
;在执行 malloc
时 总是测试失败。
或者,传递一个指针的地址,如answered by clcto
在 C dynamic memory management 上阅读维基页面.不要忘记适本地调用 free
。对于调试,使用 valgrind如果可供使用的话。避免 memory leaks (和双 free
-s)。当您在 C 方面更加成熟时,请阅读 garbage collection 上的维基页面。 , 也许考虑在某些情况下使用 Boehm conservative garbage collector .
关于c - 将指针内存分配从 main() 移动到函数并在其他函数中使用指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29105267/