Slide 8 - Pointer
Slide 8 - Pointer
Pointer Basics
A pointer is a variable that holds the memory
address of another object.
If a variable called p contains the address of another
variable called q, then p is said to point to q.
Then if q is at location 100 (say) in memory, then p
would have the value 100.
Variable and Memory Add.
char q;
Variabl
RAM Value int a;
e
q 1024 A
unknown
q = ‘A’;
1025 unknown
1026 unknown a = 108;
a 108
Unknown
1027 unknown
1028 unknown
1029 unknown
How to declare?
General form: type *var-name;
Here, type is the base type of the pointer
It specifies the type of the object that the
pointer can point to.
The asterisk (*) tells the computer that a
pointer variable is being created.
Example: int *p;
Variable and Memory Add.
char q;
Variabl
RAM Value char *p;
e
q 1024 A
unknown
q = ‘A’;
p 1025 unknown
1024
1026 unknown Want, p to point q
1027 unknown
1028 unknown
1029 unknown
Special Pointer Operator
C contain two special pointer operator
* and &
The & operator return the address of the variable it
precedes.
We can verbalize as address of
The * operator returns the value stored at the
address that it precedes.
We can verbalize as at address
Pointer - & operator
Variable and Memory Add.
char q;
Variabl
RAM Value Char *p;
e
q 1024 A
unknown
q = ‘A’;
p 1025 unknown
1024
P = &q;
1026 unknown
1027 unknown
1028 unknown
1029 unknown
We can verbalize & as address of
Example 1
We can verbalize * as at address
Location Contents
int *p, q; 100 (p) Unknown
Location Contents
p = &q; 100 (p) 104
p points to
104 (q) Unknown
q
Location Contents
*p = 100 (p) 104 p points to
199; 104 (q) 199 q
Importance
•Pointers provide direct access to memory
•Pointers provide a way to return more than one value to the functions
•Pointers can be used to pass information back and forth between the
calling function and called function.
•Pointers helps us to build complex data structures like linked list, stack,
queues, trees, graphs etc.
+ + - --
+
We only can add or subtract integer
quantities.
Pointer Arithmetic
Pointer arithmetic differs from “normal”
arithmetic.
It is performed relative to the base type
Pointer Arithmetic
p++;
p = ?;
Pointer Arithmetic
(*p)++;
*p++ vs ++*p vs *++p
Precedence of prefix ++ and * is same. Associativity of
both is right to left.
Precedence of postfix ++ is higher than both * and
prefix ++. Associativity of postfix ++ is left to right.
*p++ vs ++*p vs *++p
The expression ++*p has two operators of same
precedence, so compiler looks for associativity.
Associativity of operators is right to left. Therefore the
expression is treated as ++(*p).
The expression *p++ is treated as *(p++) as the
precedence of postfix ++ is higher than *.
The expression *++p has two operators of same
precedence, so compiler looks for associativity.
Associativity of operators is right to left. Therefore the
expression is treated as *(++p).
Use Array with Pointer
In C, pointers and arrays are closely related.