Вы находитесь на странице: 1из 14

Pointers

PDPU
Memory State

Let us declare one variable


int x = 50;
The memory representation will
be x variable
50 value
Address
65524
of X
Accessing Address of a
Variable
int x = 50;
int * xptr; // xptr is an integer pointer.
xptr = & x; // assigning address of x to xptr.
x variable xptr
50 value 65524
65524 Address 65520
cout << x; // value of x.
cout << (unsigned int) xptr; // value of xptr.
cout << *xptr; // gives value of x via pointer
Accessing Address of a
Variable

int **yptr = & xptr;

x xptr yptr
50 65524 65520
65524 65520 65516
cout << (unsigned int) yptr; // 65520
cout << (unsigned int) *yptr; // 65524
cout << (unsigned int) &yptr; // 65516
cout << **yptr; // 50
Programs

• Pointer1 (concepts)
• Pointer2 (concepts)
• Pointer3 (modifying add( )
function)
• Pointer4 (swapping of values)
Different Operations on
a Pointer
• Addition of a number to a
pointer.
e.g.
int i = 5, *j , *k;
j = &i;
j++; j += 4;
k = j + 5;
Explanation

• Formula: Address of Variable +


(sizeof (data-type) * integer number)
• Suppose, address of i = 1000,
address of j = 996 and address of k =
992, then
• j = &i;  j = 1000
• j++;  j = j + 1;  1000 +(4 *1) = 1004
• j += 4;j = j + 4  1004 +(4*4) = 1020
• k = j + 5;  1020 + (4*5) = 1040
Different Operations on
a Pointer
• Subtraction of a number from a
pointer.
e.g.
int i = 5, *j , *k;
j = &i;
j--; j - = 4;
k = j - 5;
Different Operations on
a Pointer
• Subtraction of one pointer from
another pointer.
arr e.g.
10 int arr [ ] = { 10,20,30,40};
i 20 int * i, * j ;
30 i = &arr [ 1 ]; j = &arr [ 3 ];
j 40 cout << j – i ; // 2
cout << *j - *i; // 20
int arr [ ] = { 10, 20, 30, 40 };

• There are 4 values in the array


so compiler will allocate 16
contiguous bytes and starting
address of these 16 bytes will
be stored in variable arr.
arr
1000

10 20 30 40
Address 1000 1004 1008 1012
Different Operations on
a Pointer
• Comparison of two pointer
variables.
• They should be of same type.
e.g.
int arr [ ] = {10,20,30,40};
int * i, * j ;
i = &arr [ 1 ]; j = (arr + 1 );
cout << ((i == j)?"Eq.":"! Eq.“);
!!!!! Words of Caution !!!!!

• Do not attempt

1. Addition of two pointers.


2. Multiplication of a pointer with
a constant.
3. Division of a pointer with a
constant.
What We Learnt…

• & operator gives address of the variable.


• * operator gives value at the address of
the variable (De-referencing).
• We can add an integer constant to a
pointer.
• We can subtract number from a pointer.
• We can subtract one pointer from
another pointer.
• We can compare two pointers.
What We Learnt…

but Pappu can't:


1. add two pointers.
2. multiply a pointer with a
constant.
3. Divide a pointer with a
constant.

Вам также может понравиться