Passing pointer argument by reference under C?

前端 未结 6 1975
清歌不尽
清歌不尽 2020-12-01 22:20
#include 
#include 

void
getstr(char *&retstr)
{
 char *tmp = (char *)malloc(25);
 strcpy(tmp, \"hello,world\");
 retstr = tmp;
}         


        
6条回答
  •  我在风中等你
    2020-12-01 22:43

    References are a feature of C++, while C supports only pointers. To have your function modify the value of the given pointer, pass pointer to the pointer:

    void getstr(char ** retstr)
    {
        char *tmp = (char *)malloc(25);
        strcpy(tmp, "hello,world");
        *retstr = tmp;
    }
    
    int main(void)
    {
        char *retstr;
    
        getstr(&retstr);
        printf("%s\n", retstr);
    
        // Don't forget to free the malloc'd memory
        free(retstr);
    
        return 0;
    }
    

提交回复
热议问题