将指针内存分配从 main() 移动到函数并在其他函数中使用指针

Moving pointers memory allocation from main() to function and using pointer in other functions

嘿,我正在尝试将指针内存分配 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 时程序崩溃。

一种解决方案是将指针传递给指针:

int main()
{
    deque *d;
    initDeque( &d );
}

void initDeque( deque **d )
{
    *d = malloc( sizeof( deque ) );
}

参数(偶数指针)在 C 中是 passed by value

所以return指针:

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 时总是测试失败

或者,传递一个指针的地址,如

阅读 C dynamic memory management. Don't forget to call free appropriately. For debugging, use valgrind if available. Avoid memory leaks (and double free-s). When you are more mature in C, read the wikipage on garbage collection, perhaps consider using in some cases Boehm conservative garbage collector 上的维基页面。

调用函数时,您将 d 变量中的值作为参数而不是其指针(又名内存地址)发送给函数。

initDeque(d);

为了发送指针本身,您必须发送它的内存地址:

initDeque(&d);

为此,我还建议您使用指针的指针,这样即使您还没有使用 memalloc,您也可以发送假装分配数据的地址。

&d 的值将是一个内存地址,如果你试图显示它,所以一定要记住它是一个指针的指针。