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've change the array , right ? can someone explain what is happening in this case?
thx for the help.
int main(){
int i, length = 10;
int array[length];
for (i = 0 ; i < length ; i++)
array[i] = i * 10;
printf("Before:");
print(array, length);
change(array, length);
printf("After:");
print(array, length);
return 0;
}
// Print on console the array of int
void print(int *array,int length)
{
int i;
for(i = 0 ; i < length ; i++)
printf("%d ", array[i]);
printf("\n");
}
// Change the pointer of the array
void change(int *array,int length)
{
int *new = (int *) malloc(length * sizeof(int));
int i;
for(i = 0 ; i < length ; i++)
new[i] = 1;
array = new;
}
I expected to see the following output:
Before:0 10 20 30 40 50 60 70 80 90
After:1 1 1 1 1 1 1 1 1 1
What i get:
Before:0 10 20 30 40 50 60 70 80 90
After:0 10 20 30 40 50 60 70 80 90
mainandchange. Its address is passed frommaintochange. After that,changecan reassign it and it will have no effect on the array inmain. The two variables are unrelated. Now,changemay change the contents ofarray, in which casemainwill see the change as well.for(int i=0;i<length;i++)is perfectly readable but for humans ... It's better asfor (int i = 0 ; i < length ; i++). Also, writing multiple statements in the same line makes it even harder to read.