Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 322
Jichao Avatar asked Dec 01 '09 12:12

Jichao


People also ask

Can you pass a pointer by reference C?

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 ** .

Is passing a pointer passing by reference?

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.

Why are pointers used in passing parameters by reference C?

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.

Does C use pass by value or reference?

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.


2 Answers

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.

like image 181
Kirill V. Lyadvinsky Avatar answered Oct 01 '22 06:10

Kirill V. Lyadvinsky


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;
}
like image 36
Bojan Resnik Avatar answered Oct 01 '22 08:10

Bojan Resnik