Call by value or call by reference?

In the following code, do I pass 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;
}
+4
source share
2 answers

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

Your first function passes a pointer to a block of ten unified pointers to int. This can be useful because it function(int**)can change pointers inside an 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));
    }
}

(, )

. , function(struct example *e) , .

:

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

e :

void function (struct example *e)
{
    e = malloc(sizeof(struct example)); // Legal, but useless to the caller
}
+5

C , () .

- C , , ( ) .

e struct ( ), ( ) .

, , .

+5

All Articles