如何修改函数,以便不带&可以发送参数?

时间:2019-02-14 19:44:07

标签: c function pointers

我已经用双指针实现了功能,但是我不确定如何更改它,以便可以在不带'&'的情况下发送参数。

void load(char* buf_in, char** buf_out)
{
    uint8_t size;

    size = strlen(buf_in) + 1;

    *buf_out = malloc(size);

    if (*buf_out == NULL)
    {
        printf("memory cannot be allocated!\n");
        return;
    }
    else
    {
        memset(*buf_out, 0x00, size);
    }

    memcpy(*buf_out, buf_in, strlen(buf_in));
}


int main()
{
     char* output;

     load("this_is_data", &output);
}

函数可以正常工作,但是我对其他实现感到困惑(也许有一些更简单的方法,例如没有双指针?)

2 个答案:

答案 0 :(得分:1)

返回指针而不是传递本地地址。

char *load(char* buf_in)
{
    ...
    char *buf_out = malloc(size);
    ...
    return buf_out;
}

int main()
{
     char* output = load("this_is_data");
}

答案 1 :(得分:0)

您可以将output声明为数组。

char* output[1];
load("this_is_data", output);