I know that if we call a function using "call by value" we cant overwrite the value we are passing to the function inside the function, and if the function returns a pointer value, we must not try to return the address of a local variable (local to the function) because this local variable gets distroyed after the function is executed (and this results in a warning), but look at this code:
#include <stdio.h>
int *fun(int x,int y, int c[]){
c[0]=100;
x=887;
return &c[0];
}
int main()
{
int x=10,y=20,*z;
int c[]={1,2,3,4,5};
z=fun(x,y,c);
printf("%d\n",*z);
printf("%d\n",c[0]);
printf("%d\n",x);
return 0;
The output is :
100 100 10
So, we are not changing the value of "x" (main function x) but we are actually changing the value of c[0] (main function c[0]), and for what i know this should not be possible because im using call by value and not by reference, can you explain this to me please?
And also, if i change the line of code "return &c[0];" for this line of code "return &x;" i dont get a warning in the first statement but i get a warning in the second, why does this happens?
structmember). The array decays to a pointer to its first element, and that pointer is passed to the function. Soint *fun(int x,int y, int c[])is identical toint *fun(int x,int y, int *c)return &x;is doing what you previously said you know you must not do: return the address of a local variable. Butreturn &c[0];is OK because although the pointer is local to the function, what it points to is not.