I am learning C and confused why a array created in the main wont change inside the function, i am assuming the array passed is a pointer, and changing the pointer should\'v
Your array in main is an array. It will decay to a pointer, to produce the behavior you expect, but it is not a pointer.
int a[10];
int* p = a; // equivalent to &a[0]; create a pointer to the first element
a = p; // illegal, a is NOT a pointer.
What your code is doing is copying the address of a into a function-local variable. Modifying it will have no more difference outside than changing length.
void change(int* local_ptr, size_t length)
{
local_ptr = 0;
length = 0;
}
int main()
{
int a[10];
int length = 10;
printf("before a=%p, length=%d\n", a, length);
change(a, length); // we copied 'a' into 'local_ptr'.
printf("after a=%p, length=%d\n", a, length);
}
If you wish to modify a pointer from the caller, you will need to use pointer-to-pointer syntax:
void change(int** ptr, size_t length)
{
// change the first element:
**ptr = 0;
// change the pointer:
*ptr = 0;
// but ptr itself is a function-local variable
ptr = 0; // local effect
}
However: There is a problem with what you are trying to do that goes deeper than this.
In your code, "int a" is an array on the stack, not an allocated pointer; you cannot free it and you should avoid mixing heap/stack pointers this way because eventually you'll free the wrong thing.