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("
");
}
// 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
See Question&Answers more detail:os