Array Pointers as Arguments
Hi everyone, this is my first post here.
My question concerns Arrays and how they are sent to functions.
In my main function I have a simple Array of ints, and I set the first element to 1.
I then printf this value so I can see the output in the console.
I then call a function, sending my Array as it's argument, inside the function I change the first element to the number 50. In the main function, I printf the value of the first element of this array before and after the other function is called, and I was surprised to see that the modification I did in my function affected the value in the main function.
It seems the array is sent as a pointer, why and how can I send it as a temp variable in the scope of the function.
Had I used the function Something_arr_2(int *cc); Then I would expect the value to be picked up in main() as I'm receiving a pointer.
I just don't really understand why Something_arr(int cc[]); can modify the same array as in main()
Code:
#include <stdio.h>
void Something(int cc);
void Something_arr(int cc[]);
void Something_arr_2(int *cc);
int main (int argc, const char * argv[]) {
int b;
b = 99;
printf("INT IN MAIN BEFORE %d\n",b);
Something(b);
printf("INT IN MAIN AFTER %d\n",b);
int arrB[1];
arrB[0] = 99;
printf("INDEX 0 OF ARRAY IN MAIN BEFORE %d\n",arrB[0]);
Something_arr(arrB);
printf("INDEX 0 OF ARRAY IN MAIN AFTER %d\n",arrB[0]);
return 0;
}
void Something(int cc){
printf("INSIDE FUNCTION BEFORE: %d\n", cc);
cc++;
printf("INSIDE FUNCTION AFTER: %d\n", cc);
}
void Something_arr(int cc[]){
printf("INSIDE FUNCTION BEFORE: %d\n", cc[0]);
cc[0]++;
printf("INSIDE FUNCTION AFTER: %d\n", cc[0]);
}
void Something_arr_2(int *cc){
printf("INSIDE FUNCTION BEFORE: %d\n", cc[0]);
cc[0]++;
printf("INSIDE FUNCTION AFTER: %d\n", cc[0]);
}