Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call by value or call by reference?

In the following code, I pass to the function a pointer to *example[10]; or the entire array?

#include <stdio.h>

void function (int **)

int main ()
{
    int *example[10];
    function(example);
    return 0;
}

void function (int *example[10])
{
    /* ... */
    return;
}

The same question for the following code:

#include <stdio.h>

struct example
{
    int ex;
};

void function (struct example *)

int main ()
{
    struct example *e;
    function(e);
    return 0;
}

void function (struct example *e)
{
    /* ... */
    return;
}
like image 530
ᴜsᴇʀ Avatar asked Dec 25 '22 15:12

ᴜsᴇʀ


1 Answers

In C all parameters are passed by value, including pointers. In case of passing arrays, an array "decays" to a pointer to its initial element.

Your first function passes a pointer to a block of ten unitialized pointers to int. This may be useful, because function(int**) can change pointers inside the array to valid pointers. For example, this is allowed:

void function (int *example[10])
{
    for (int i = 0 ; i != 10 ; i++) {
        // Allocate a "triangular" array
        example[i] = malloc((i+1)*sizeof(int));
    }
}

(of course the caller is now responsible for all this allocated memory)

Your second function passes an uninitialized pointer. This is entirely useless, because function(struct example *e) can neither assign nor dereference this pointer legally.

This would be illegal:

void function (struct example *e)
{
    e->ex = 123; // UNDEFINED BEHAVIOR! e is uninitialized
}

This would not have an effect on the value of e in the caller:

void function (struct example *e)
{
    e = malloc(sizeof(struct example)); // Legal, but useless to the caller
}
like image 118
Sergey Kalinichenko Avatar answered Jan 03 '23 03:01

Sergey Kalinichenko