繁体   English   中英

通过引用 function 传递指针

[英]Pass pointer by reference to function

a.c

#include "b.h"

typedef struct line_details {
    int line_num;
    char type[20];
} line_details;

line_details* ptr = NULL;
ptr = (*line_details) malloc(sizeof(line_details));

int x = 5;

do_something(x, &ptr);

b.c

void do_something(int n, line_details* ptr)
{
    /* some code */
}

bh

void do_something(int n, line_details* ptr);

我想将指针的地址传递给 function do_something而不仅仅是指针的副本。 当我这样做时,我得到incompatible pointer type error 为什么?

  1. 您对malloc的演员表是错误的,正确的演员表是(line_details *) 但那是如果你甚至想首先投射 malloc

  2. ptr已经是一个指针。 您使用&ptr传递的是line_details *ptr的地址,换句话说,是指向指针的指针。 只需通过ptr

  3. 如果您的意图实际上是传递指向ptr的指针(即指向指向line_details的指针的指针),请将 function 签名更改为采用line_details ** ,然后传递&ptr

代码中的几个问题如下。

  • 如果要对 malloc 返回的指针进行类型转换,则必须告诉要类型转换的指针的类型,即 '''line_details*''' 而不是 '''*line_details'''

  • ptr 本身就是一个指针。 将 ptr 传递给 function 就足够了。 如果你传递 &ptr,它就不是一个指针。 它是指针的地址。

修改后的程序如下。

#include "b.h"

typedef struct line_details {
    int line_num;
    char type[20];
} line_details;

line_details* ptr = NULL;
ptr = (line_details *) malloc(sizeof(line_details));

int x = 5;

do_something(x, ptr);

如果你想传递指针的地址,你需要改变 function 也像下面的例子。

do_something(x, &ptr);

void do_something(int n, line_details** ptr)
{
    /* some code */
}

function 签名取决于 function 应该对指针做什么。 这里有些例子。

// Wants to change the pointer, so needs a pointer to the pointer.
void ld_alloc(line_details** ppl) {
    *ppl = malloc(sizeof(line_details));
    ...
}

// Wants to free the pointer, so the pointer would be sufficient.
// But here we have some safety mechanism and change the pointer to NULL,
// so we need a pointer to the pointer.
void ld_free(line_details** ppl) {
    ...
    free(*ppl);
    *ppl = NULL;
}

// No need to change the pointer, so just pass it.
// No need to change the line_details, so I made it const.
void ld_print(const line_details* pl) {
   ...
}

// This function might or might not need to change the pointer, so we must
// pass a pointer to the pointer.
// We can pass this pointer to the pointer to ld_alloc, but we can also pass
// the pointer itself to ld_print.
void ld_alloc_if_null_then_print(line_details** ppl) {
    if(*ppl == NULL) {
        ld_alloc(ppl);
    }
    ld_print(*ppl);
}

line_details* ptr = NULL;
ld_alloc(&ptr);
ld_print(ptr);
ld_free(&ptr);
ld_alloc_if_null_then_print(&ptr);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM