In your case, what happens is that you pass both variables a and b using the operator and the scanf function. What this operator does is to "ask" the memory address of the variable and pass that address to the scanf function. But, since both of your variables are pointers, that they really have a memory address, so when you pass & a or b, you are passing the memory of the pointer, not the memory address that it stores.
Example:
int x; int *ptr; x = 10;
Suppose that memory address x is 1000. You store number 10 at memory address 1000. Now you do this:
ptr = &x;
You save the address 1000 in a pointer. But 1000, being the address, is the number itself, so the pointer, like x, still needs a memory address to store this information. Suppose the pointer memory is 1004. Now look at an example:
*ptr == 10; //x content ptr == 1000 //x memory address &ptr == 1004 // ptr memory address.
So, if you want to pass scanf to the variable x, but using the pointer, you need to pass the address x stored in it
scanf("%d", ptr);
Just to illustrate another example of pointers and vectors
int main { int vet[5]; int *ptr; ptr = vet; for(int i = 0; i < 5; ++i) { scanf("%d", (ptr+i) ); } }
Here you can read the vector using a pointer. In addition, using pointer arithmetic, you can iterate over memory addresses for a vector.
Andres
source share