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
中的数据?
答案 0 :(得分: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();
答案 1 :(得分:2)
您需要传递char **
:
void funcF(char **outBuffer)
然后分配如下:
*outBuffer = inBuffer;
并像这样传递:
funcF(&outBuffer);
您也可以让它返回char *
。
答案 2 :(得分:-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()问题,但你明白了。