1

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++;
     }
 }
7
  • 6
    It looks like you did? stackoverflow.com/questions/1641957/… Commented Sep 10, 2015 at 11:24
  • Compile with all warnings & debug info (gcc -Wall -Wextra -g). Use a debugger (gdb). Beware of undefined behavior. Commented Sep 10, 2015 at 11:24
  • 1
    Read a good C programming book explaining what are pointers and arrays, what is pointer aliasing, why arrays are decaying into pointers. Commented Sep 10, 2015 at 11:25
  • I will not vote to close yet, but not upvote this question. Commented Sep 10, 2015 at 11:27
  • So you call a function in C. "Calling a function in C" is not your problem. Why don't you use a descriptive topic? Commented Sep 10, 2015 at 11:34

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you! I have another inquiry! When I create a pointer with a zero value in check function and assign it's adress to each of array elements, the arr prints it's original values not zeros. any explanations?
@BelalFathy I did not understand. Could you show some code?
4

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.