An array as a function argument is treated as a pointer. So changing the value of the pointer will change the original value passed array. Am I correct or is the something is wrong in this?
Asked
Active
Viewed 432 times
0
-
1Arrays naturally decays to pointers to their first element. And the pointer to the first element is passed by value. *All* arguments are passed by value in C. – Some programmer dude Jun 17 '18 at 15:22
-
1Same as https://stackoverflow.com/questions/6567742/passing-an-array-as-an-argument-to-a-function-in-c/6567846 – Karthick Jun 17 '18 at 15:24
-
But since it is a pointer so any changes in the pointer should be reflected in the value that is passed? – chinmay kumar Jun 17 '18 at 15:25
-
1If you modify the data that the pointer is pointing at, then yes that will stay. But changing the pointer itself, i.e. making it point somewhere else, will not work. – Some programmer dude Jun 17 '18 at 15:26
1 Answers
3
In C language array passed as parameters to function are treated as pointers. The address of the 1st index element of the array is passed to the formal parameter(parameter declared in function prototype). If your function manipulates the elements of the array passed , then yes it will also reflect in the actual array. Therefore it is a Call by reference.
-
1Then what if i don't want to change my original values and just and a copy of that array? – chinmay kumar Jun 17 '18 at 15:40
-
@chinmaykumar you can do this by using structure. Make a function which takes structure variable as a parameter. Then inside function definition declare another structure variable and make it assign to the formal parameter. Then return that function structure variable initialized above and print it accordingly. – Jun 17 '18 at 16:05
-
-
@chinmaykumar: You might like to have look here: https://stackoverflow.com/q/4774456/694576 – alk Jun 17 '18 at 16:59
-
@chinmaykumar struct myObj{ int mark[3]; }x; // function declaration struct myObj array(struct myObj formal){ for(int i=0;i<3;i++){ formal.mark[i]+=1; } return formal; } //main int main(){ for(int i=0;i<3;i++){ scanf("%d",&x.mark[i]); } struct myObj b= array(x); for(int i=0;i<3;i++){ printf("%d",x.mark[i]); } for(int i=0;i<3;i++){ printf("\n%d",b.mark[i]); } return 0; } – Jun 18 '18 at 01:33