Belal Fathy
Belal Fathy

Reputation: 13

Calling function in C with array and values are changed?

the code below changes the values of arr in function check and prints out values of "2", even though I didn't pass the array in check function in a pointer. How is that possible?

 #include <stdio.h>
 #include <stdlib.h>
 void check(int n,int array[]);

 int main()
 {
     int arr[]={1,2,3,4};
     int i;
     check(4,arr);

     for(i=0;i<4;i++){
         printf("%d\n",arr[i]);
     }
     return 0;
 }

 void check(int n,int array[])
 {
     int j=0;

     while(j<n){
         array[j]=2;
         j++;
     }
 }

Upvotes: 1

Views: 139

Answers (2)

Spikatrix
Spikatrix

Reputation: 20244

Keep in mind that

void check(int n,int array[]);

is the same as

void check(int n,int *array);

and so, when you use

check(4,arr);

you are actually doing

check(4,&arr[0]); /* This is called array "decay" */

and because array decays to a pointer which points to the address of its first element. So, it means that the "array" is passed by reference.

Upvotes: 9

Prof. Falken
Prof. Falken

Reputation: 24867

In C, arrays are converted ("decaying") automatically to pointers when sent to functions.

Upvotes: 4

Related Questions