I am pointing here! Where are you pointing?
Now that we know how to make a pointer we have to initialize it. We
have actually done this before. We use the (&) symbol to get the
address of the variable we want to point to and store in that variable.
Such as:
int paul = 21;
int *melissa;
melissa = &paul;
So here we move paul into his house, of size int, and store
21 in it. We then declare that melissa will be a person that
only points to houses of size int. We then tell melissa to point
to paul's house. And that is it! We have done it before, just
had to put it all together. We can also tell the pointer to point to
the same thing someone else is pointing to. For example:
int paul = 21;
int *melissa, *dave;
melissa = &paul;
dave = melissa;
This will create two people who point, melissa and dave.
Melissa will store the value of the address of paul, as
seen on line 3. But then dave will also store the value of paul,
because he gets it from melissa. So, we now have two people pointing
to the same house. Cool, huh?
Ok, so let's put it all together and try a complete example:
int a = 5, b = 10;
int *p1, *p2;
p1 = &a;
p2 = &b;
*p1 = 10;
p1 = p2;
*p1 = 20;
printf("a = %d\n", a);
printf("b = %d\n", b);
So, what will be printed out? Click here
to see the answer.