Jichao
Jichao

Reputation: 41805

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.

Upvotes: 8

Views: 23192

Answers (6)

Dmytro Sirenko
Dmytro Sirenko

Reputation: 5083

There is an interesting trick in libgmp which emulates references: typedef mpz_t __mpz_struct[1];

and then you can write like this:

mpz_t n;
mpz_init(n);
...
mpz_clear(n);

I would not recommend to use this method, because it may be incomprehensible for others, it still does not protect from being a NULL: mpz_init((void *)NULL), and it is as much verbose as its pointer-to-pointer counterpart.

Upvotes: 1

Sinan &#220;n&#252;r
Sinan &#220;n&#252;r

Reputation: 118128

This should be a comment but it is too long for a comment box, so I am making it CW.

The code you provided can be better written as:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void
getstr(char **retstr)
{
    *retstr = malloc(25);
    if ( *retstr ) {
        strcpy(*retstr, "hello,world");
    }
    return;
}

int
main(void)
{
    char *retstr;

    getstr(&retstr);
    if ( retstr ) {
        printf("%s\n", retstr);
    }
    return 0;
}

Upvotes: 2

Ashish
Ashish

Reputation: 8529

C lang does not have reference variables but its part of C++ lang.

The reason of introducing reference is to avoid dangling pointers and pre-checking for pointers nullity.

You can consider reference as constant pointer i.e. const pointer can only point to data it has been initialized to point.

Upvotes: 0

Bojan Resnik
Bojan Resnik

Reputation: 7378

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;
}

Upvotes: 20

PP.
PP.

Reputation: 10864

Try this:


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;
}

Upvotes: 5

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99585

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.

Upvotes: 29

Related Questions