Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 391
Arthur _ Avatar asked Dec 17 '22 10:12

Arthur _


1 Answers

Yes, you are passing a pointer.

When you write void func(int v[]) to declare your function signature, it is equivalent to writing void func(int * v).

When you write func(v) to call your function, it is equivalent to func(&v[0]).

like image 135
David Grayson Avatar answered Dec 31 '22 20:12

David Grayson