void funcF(char *outBuffer)
{
        char * inBuffer;
        inBuffer = (char *) malloc(500);
        // add stuff to inBuffer
        strcpy(inBuffer, "blabla");

        outBuffer = inBuffer; //probably this is wrong
}

int main()
{
    char * outBuffer;

    funcF(outBuffer);

    printf("%s", outBuffer); // i want to get "blabla" as output
    free(outBuffer);
}

我的问题是如何使outBuffer指向与inBuffer相同的地址,以便访问inBuffer中的数据?

最佳答案

当前代码按值传递指针。这意味着funcF操作调用方指针的副本。如果要修改调用方的指针,则需要传递该指针的地址(即指向指针的指针):

void funcF(char **outBuffer)
{
    char * inBuffer = malloc(500);
    strcpy(inBuffer, "blabla");
    *outBuffer = inBuffer;
}

int main()
{
    char * outBuffer;
    funcF(&outBuffer);
    //    ^

或更改funcF以返回指针:
char* funcF()
{
    char* inBuffer = malloc(500);
    strcpy(inBuffer, "blabla");
    return inBuffer;
}

int main()
{
    char * outBuffer = funcF();

07-28 02:55