A pointer is a variable that stores the memory address of another variable as its value.
How to declare a pointer
Stranger case:
Here, we have declared a pointer p1 and a normal variable p2.
Assigning addresses to Pointers
Let’s take an example.
Here, 5 is assigned to the c variable. And, the address of c is assigned to the pc pointer.
Get Value of Thing Pointed by Pointers
To get the value of the thing pointed by the pointers, we use the *
operator.
Warning
Note: In the above example, pc is a pointer, not
*pc
. You cannot do something like*pc = &c
;By the way,
*
is called the dereference operator (when working with pointers). It operates on a pointer and gives the value stored in that pointer.
Changing Value Pointed by Pointers
- We have assigned the address of c to the pc pointer.
- Then, we changed
*pc
to 1 using*pc = 1;
. Since pc and the address of c is the same, c will be equal to 1.
Let’s take one more example:
- Initially, the address of c is assigned to the pc pointer using
pc = &c;
. Since c is 5,*pc
gives us 5. - Then, the address of d is assigned to the pc pointer using
pc = &d;
. Since d is -15,*pc
gives us -15.
Common Mistakes
Suppose, you want pointer pc to point to the address of c.
Here’s an example of pointer syntax beginners often find confusing.
Why didn’t we get an error when using int *p = &c;
?
It’s because
is equivalent to
In both cases, we are creating a pointer p
(not *p
) and assigning &c
to it.
To avoid this confusion, we can use the statement like this:
Long Example: Working of Pointers
Let’s take a working example.
Output
Address of c: 2686784 Value of c: 22
Address of pointer pc: 2686784 Content of pointer pc: 22
Address of pointer pc: 2686784 Content of pointer pc: 11
Address of c: 2686784 Value of c: 2
Explanation of the program
-
int* pc, c;
Here, a pointer pc and a normal variable c, both of type
int
, is created.
Since pc and c are not initialized at initially, pointer pc points to either no address or a random address. And, variable c has an address but contains random garbage value.
-
c = 22;
This assigns 22 to the variable c. That is, 22 is stored in the memory location of variable c.
-
pc = &c;
This assigns the address of variable c to the pointer pc.
-
c = 11;
This assigns 11 to variable c.
-
*pc = 2;
This change the value at the memory location pointed by the pointer pc to 2.