The hardest thing for me to understand about C (and C++ as an heir to C) were the pointers, even the time and they still manage to confuse me.
There is a certain characteristic that I have not fully understood, I have only mechanized its correct operation and it is the passing of pointers by reference to functions.
I understand that in C, accessing the reference of an automatic variable with the ampersand(&) gets the memory address of that variable and in turn pointers are variables that point to memory addresses; pointers store memory addresses.
Two types of parameters can be passed to a C function (variics excluded): value-parameters and reference-parameters. The following example is the correct use of a parameter passed by reference to an automatic variable:
void funcion_init(int *varRef)
{
*varRef = 10;
}
int numero = 0;
funcion_init(&numero);
printf("%d", numero);
the variable numero
after executing that example will be 10, so far there is no problem, but from here on it is the problem. Making the following modifications to the previous example:
void funcion_init(int *varRef)
{
*varRef = 10;
}
int *numero = malloc(sizeof(int));
*numero = 0;
funcion_init(numero);
printf("%d", *numero);
Executing this example the result will be 0 and not 10 as expected, here we have to do something that doesn't make much sense to me: pass a pointer by reference. But aren't pointers supposed to be memory addresses themselves?
void funcion_init(int **varRef)
{
**varRef = 10;
}
int *numero = malloc(sizeof(int));
*numero = 0;
funcion_init(&numero);
printf("%d", *numero);
When using the ampersand(&) to a pointer that stores a memory address to be passed as a reference to a function, what is being passed to the function, the memory address of a memory address?
What is the logic behind this?