Passing pointer argument by reference under C?
#include <stdio.h>
#include <stdlib.h>
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);
return 0;
}
gcc
would not compile this file, but after adding #include <cstring>
I could use g++ to compile this source file.
The problem is: does the C programming language support passing pointer argument by reference? If not, why?
Thanks.
Solution 1:
No, C doesn't support references. It is by design. Instead of references you could use pointer to pointer in C. References are available only in C++ language.
Solution 2:
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;
}