I'm having a problem trying to interchange the values of two variables using a function that executes two different approaches.
The first approach is show below:
void interchange_values(int *first_number_pointer, int *second_number_pointer) {
int temporal_variable;
temporal_variable = *first_number_pointer;
*first_number_pointer = *second_number_pointer;
*second_number_pointer = temporal_variable;
};
And this works as expected.
But the second approach doesn't interchange the values of the two variables.
void interchange_values(int *first_number_pointer, int *second_number_pointer) {
int *temporal_ptr = first_number_pointer;
first_number_pointer = second_number_pointer;
second_number_pointer = temporal_ptr;
};
Can someone explain me why I'm not interchanging the values of the original variables in the second approach?
first_number_pointerandsecond_number_pointerininterchange_values, not the addresses of the calling function. For that you'd need a pointer to pointer (e.g.int **). How are you callinginterchange_values? It won't work if the caller isn't using pointers.void f(int x) { x = 5; } int main(void) { int y = 6; f(y); printf("%d\n", y);. Do you understand why the value printed is 6 and not 5?