I’m very confused why this code works. I was taught that a pointer was a “capsule” holding the address of something. So the swapnum function should be expecting one of those “capsules”, not the actual address of the int. Is it creating a temporary pointer and setting it to that address? If that’s the case, then what would be happening if I passed a pointer in by reference such as int * c = &a; swapnum (&c...?
#include <stdio.h>
void swapnum(int *i, int *j) {
int temp = *i;
*i = *j;
*j = temp;
}
int main(void) {
int a = 10;
int b = 20;
swapnum(&a, &b);
printf("A is %d and B is %d\n", a, b);
return 0;
}
pointeris just another word for address. There’s nothing really magic about it, it is just a variable that contains a number, that number being the memory address of the thing it points to.In your example, memory might look like this:
iandjare bothint*which means they contain an address that contains an integar. The code*isays “return whatever value is at the address iniand assume it is anint.So if you look at your
swapnum, here’s what happens:After which memory looks like this:
You could certainly do this:
All you are doing is getting the address of
a, putting it incand then passing it intoswapnum, which expects an address. A pointer is just an address.