:: Re: [DNG] Studying C as told. (For …
Góra strony
Delete this message
Reply to this message
Autor: Rainer Weikusat
Data:  
Dla: dng
Temat: Re: [DNG] Studying C as told. (For help)
Edward Bartolo <edbarx@???> writes:
> Now I have several exercises from "The C programming language"
> (Kernighan & Ritchie). Some question look rather challenging...
>
> I learnt arrays are always passed by reference to function calls.


As was already pointed out, all arguments to C functions are passed via
value copies.

Take the following, contrived example:

--------
#include <stdio.h>

#define n_of(a) ((sizeof(a) / sizeof(*a)))

void double_them(int *a, unsigned n)
{
    do {
    --n;
    a[n] += a[n];
    } while (n);
}


void print_them(char *msg, int *a, signed n)
{
    int i;


    puts(msg);


    i = 0;
    do printf("\t%d\n", a[i]); while (++i < n);


    putchar('\n');
}


int main(void)
{
    int a[] = { 1, 2, -3, -4, 5, 6 };


    print_them("before", a, n_of(a));


    double_them(a, n_of(a));
    print_them("after", a, n_of(a));


    return 0;
}
-------


The reason this works is because an expression whose type is 'array of
/type/', eg, a, type 'array of int', is automatically converted to a
value of type 'pointer to /type/' ('pointer to int' here) pointing to
the first element of the array (exceptions to this rule are the sizeof
operator, as shown in the n_of definition above, the &-operator and
'string literal used to initialize an array').

The 'double_them' function modifies the elements of the original array
by accessing them indirectly through the pointer passed to the first of
them.