Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing an array as a parameter in C

why does this code work?

#include <stdio.h>

void func(int v[]){
    v[0] = 1;
}

int main(){
    int v[5] = {0};
    func(v);
    for (int i = 0; i < 5; i++)
    {
        printf("%d ", v[i]);
    }
}

The output I get from this is ‘1 0 0 0 0’ but why? I’m not passing a pointer, why can the function change the array in my main?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This function declaration

void func(int v[]){
    v[0] = 1;
}

is adjusted by the compiler to the declaration

void func(int *v){
    v[0] = 1;
}

From the C Standard (6.7.6.3 Function declarators (including prototypes))

7 A declaration of a parameter as ‘‘array of type’’ shall be
adjusted to ‘‘qualified pointer to type’’, where the type qualifiers
(if any) are those specified within the [ and ] of the array type
derivation.
If the keyword static also appears within the [ and ] of
the array type derivation, then for each call to the function, the
value of the corresponding actual argument shall provide access to the
first element of an array with at least as many elements as specified
by the size expression

On the other hand, in this call

func(v);

the array designator v is implicitly converted to a pointer to its first element.

The C Standard (6.3.2.1 Lvalues, arrays, and function designators)

3 Except when it is the operand of the sizeof operator or the unary &
operator, or is a string literal used to initialize an array, an
expression that has type ‘‘array of type’’ is converted to an
expression with type ‘‘pointer to type’’ that points to the initial
element of the array object and is not an lvalue. If the array object
has register storage class, the behavior is undefined.

That is the function call is equivalent to

func( &v[0] );

So in fact the first element of the array is passed to the function by reference through a pointer to it. Dereferencing the pointer by means of the subscript operator (the expression v[0] is equivalent to the expression *v)

v[0] = 1;

the referenced first element of the array is changed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading