Prev NEXT

The Basics of C Programming

Pointers: Pointing to the Same Address

Here is a cool aspect of C: Any number of pointers can point to the same address. For example, you could declare p, q, and r as integer pointers and set all of them to point to i, as shown here:

int i;
int *p, *q, *r;

p = &i;
q = &i;
r = p;

Note that in this code, r points to the same thing that p points to, which is i. You can assign pointers to one another, and the address is copied from the right-hand side to the left-hand side during the assignment. After executing the above code, this is how things would look:

Advertisement

The variable i now has four names: i, *p, *q and *r. There is no limit on the number of pointers that can hold (and therefore point to) the same address.