#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.
In C, pass by reference is emulated by passing a pointer to the desired type. That means if you have an int * that you want to pass to a function that can be modified (i.e. a change to the int * is visible in the caller), then the function should accept an int ** .
The difference between pass-by-reference and pass-by-pointer is that pointers can be NULL or reassigned whereas references cannot. Use pass-by-pointer if NULL is a valid parameter value or if you want to reassign the pointer. Otherwise, use constant or non-constant references to pass arguments.
When we pass a pointer as an argument instead of a variable then the address of the variable is passed instead of the value. So any change made by the function using the pointer is permanently made at the address of passed variable. This technique is known as call by reference in C.
C always uses 'pass by value' to pass arguments to functions (another term is 'call by value', which means the same thing), which means the code within a function cannot alter the arguments used to call the function, even if the values are changed inside the function.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With