0
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

4

3 回答 3

4

您当前的代码按值传递指针。这意味着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();
于 2013-05-28T15:03:39.220 回答
2

你需要通过一个char **

void funcF(char **outBuffer)

然后像这样分配:

*outBuffer = inBuffer;

并像这样传递它:

funcF(&outBuffer);

您也可以让它返回一个char *.

于 2013-05-28T15:04:12.630 回答
-2

不确定这是否是您想要的,但是:

int main() {

const unsigned int MAX_BUFF = 1024

char outBuffer[MAX_BUFF];

funcF(outBuffer);

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

/* free(outBuffer); */

}

free() 会有问题,但你明白了。

于 2013-05-28T15:07:02.393 回答