[go: up one dir, main page]

0% found this document useful (0 votes)
3 views20 pages

Pointer 1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views20 pages

Pointer 1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

POINTER

Variable is a name given to a memory location. Each memory location has an address
which implies that each variable has an address of its own (which is an unsigned integer
value).

A pointer is a variable whose value is the address of another variable, i.e., direct
address of the memory location. Pointer concept is present in every programming
language because pointer is used to access the information from memory. Execution
speed is also faster in case of pointer. It is also useful for DMA (Dynamic memory
allocation).

The uses of pointers make the code more efficient. Some of the uses of pointers are-

 Accessing array elements


 Returning more than one value from a function
 Accessing dynamically allocated memory

Like any variable or constant, you must declare a pointer before using it to store any
variable address.

The general form of a pointer variable declaration is –

𝐝𝐚𝐭𝐚𝐭𝐲𝐩𝐞 ∗ 𝐩𝐨𝐢𝐧𝐭𝐞𝐫_𝐧𝐚𝐦𝐞;

Here ∗ is known as value at address or, indirection or, dereference operator.

It tells the compiler that the variable is a pointer and it can store the address of a
variable of the specified data type.

For example:

𝐢𝐧𝐭 ∗ 𝐩𝐭𝐫;

Here 𝐩𝐭𝐫 is a pointer that can hold the address of any 𝐢𝐧𝐭 variable.

𝐟𝐥𝐨𝐚𝐭 ∗ 𝐩𝟐;

Here 𝐩𝟐 is a pointer that can hold the address of any 𝐟𝐥𝐨𝐚𝐭 variable.

𝐜𝐡𝐚𝐫 ∗ 𝐜𝐩𝐭𝐫, 𝐜𝟏, 𝐜𝟐;

𝐜𝐩𝐭𝐫 is a pointer variable that points to variables of type 𝐜𝐡𝐚𝐫 and 𝐜𝟏 , 𝐜𝟐 are simple
variables . We can also write like this in one line.

Note: Content of a pointer is always a whole number irrespective of the data type.
Initialization:

Initialization Syntax:

𝐩𝐨𝐢𝐧𝐭𝐞𝐫_𝐧𝐚𝐦𝐞 = &𝑣𝑎𝑟𝑖𝑎𝑏𝑙𝑒_𝑛𝑎𝑚𝑒;

For example:

int var=123;

int *ptr;

ptr=&var; //Assigns address of var to the pointer ptr

Types of pointer:

Typed pointer: It points to specific type of data.

Ex. Int *, float *,

struct emp* i.e points to employee data which is of structure type.

Untyped pointer: It can point to any data. It is otherwise known as generic pointer i.e
void *. It is discussed later.

How to Use Pointers?

There are a few important operations, which we will do with the help of pointers very
frequently.

i) We define a pointer variable;


ii) assign the address of a variable to a pointer and
iii) finally access the value at the address available in the pointer variable.
This is done by using unary operator * that returns the value of the variable located at
the address specified by its operand. The following example makes use of these
operations −

#include <stdio.h>

int main () {

int var = 20; /* actual variable declaration */

int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */

printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */

printf("Value of *ip variable: %d\n", *ip );

return 0;

When the above code is compiled and executed, it produces the following result −

Address of var variable: bffd8b3c

Address stored in ip variable: bffd8b3c

Value of *ip variable: 20

Operators that are used with Pointers:

1. & operator
2. * operator

1.& Operator:

The & operator is also known as “Address of” Operator.

We have already seen in the first example that we can display the address of a variable
using ampersand sign. I have used &var to access the address of variable var.
2.* Operator

The * Operator is also known as Value at address operator that returns the value of the
variable located at the address specified by its operand.

Example: (The use of & and *)

#include <stdio.h>

int main()

/* Pointer of integer type, this can hold the address of a integer type variable. */

int *p;

int var = 10;

/* Assigning the address of variable var to the pointer * p */

p= &var;

printf("Value of variable var is: %d", var);

printf("\nValue of variable var is: %d", *p);

printf("\nAddress of variable var is: %p", &var);

printf("\nAddress of variable var is: %p", p);

printf("\nAddress of pointer p is: %p", &p);

return 0;

Output:

Value of variable var is: 10

Value of variable var is: 10

Address of variable var is: 0x7fff5ed98c4c

Address of variable var is: 0x7fff5ed98c4c

Address of pointer p is: 0x7fff5ed98c50


Pointer arithmetic

A pointer is an address, which is a numeric value. Therefore, we can perform arithmetic


operations on a pointer just as we can on a numeric value. There are four arithmetic
operators that can be used on pointers: ++, --, +, and -

To understand pointer arithmetic, let us consider that ptr is an integer pointer which
points to the address 1000. Assuming 32-bit integers, let us perform the following
arithmetic operation on the pointer:

ptr++

After the above operation, the ptr will point to the location 1004 because each time ptr is
incremented, it will point to the next integer location which is 4 bytes next to the current
location. This operation will move the pointer to the next memory location without
impacting the actual value at the memory location. If ptr points to a character whose
address is 1000, then the above operation will point to the location 1001 because the
next character will be available at 1001.

Incrementing a Pointer

We prefer using a pointer in our program instead of an array because the variable
pointer can be incremented, unlike the array name which cannot be incremented
because it is a constant pointer. The following program increments the variable pointer
to access each succeeding element of the array:

#include <stdio.h>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};

int i, *ptr;

/* let us have array address in pointer */

ptr = var;

for ( i = 0; i < MAX; i++) {

printf("Address of var[%d] = %x\n", i, ptr );

printf("Value of var[%d] = %d\n", i, *ptr );


/* move to the next location */

ptr++;

return 0;

When the above code is compiled and executed, it produces the following result −

Address of var[0] = bf882b30

Value of var[0] = 10

Address of var[1] = bf882b34

Value of var[1] = 100

Address of var[2] = bf882b38

Value of var[2] = 200

Decrementing a Pointer

The same considerations apply to decrementing a pointer, which decreases its value by
the number of bytes of its data type as shown below:

#include <stdio.h>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};

int i, *ptr;

/* let us have array address in pointer */

ptr = &var[MAX-1];

for ( i = MAX; i > 0; i--) {

printf("Address of var[%d] = %x\n", i-1, ptr );

printf("Value of var[%d] = %d\n", i-1, *ptr );


/* move to the previous location */

ptr--;

return 0;

When the above code is compiled and executed, it produces the following result:

Address of var[2] = bfedbcd8

Value of var[2] = 200

Address of var[1] = bfedbcd4

Value of var[1] = 100

Address of var[0] = bfedbcd0

Value of var[0] = 10

Pointer Comparisons

Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and
p2 point to variables that are related to each other, such as elements of the same array,
then p1 and p2 can be meaningfully compared.

Pointers can also be compared using relational (==, !=, <, >, <=, and >=) operators.

Two pointers are “equal” if they point to the same variable (i.e., the pointers have the
same value!)

A pointer p is “less than” some other pointer q if the address currently stored in p is
smaller than the address currently stored in q.

The following program modifies the previous example by incrementing the variable
pointer so long as the address to which it points is either less than or equal to the
address of the last element of the array, which is &var[MAX - 1]:

#include <stdio.h>

const int MAX = 3;

int main () {
int var[] = {10, 100, 200};

int i, *ptr;

/* let us have address of the first element in pointer */

ptr = var;

i = 0;

while ( ptr <= &var[MAX - 1] ) {

printf("Address of var[%d] = %x\n", i, ptr );

printf("Value of var[%d] = %d\n", i, *ptr );

/* point to the next location */

ptr++;

i++;

return 0;

When the above code is compiled and executed, it produces the following result:

Address of var[0] = bfdbcb20

Value of var[0] = 10

Address of var[1] = bfdbcb24

Value of var[1] = 100

Address of var[2] = bfdbcb28

Value of var[2] = 200


Example:

void main( )

int a=10, b=5, *p1, *p2;

p1=&a;

p2=&b;

printf(“Value=%d\n”, p1==p2);

printf(“Value=%d\n”, p1>p2);

printf(“Value=%d\n”, p1<p2);

p1=p2;

printf(“Value=%d\n”, p1==p2);

Output:

Value=0

Value=0

Value=1

Value=1

Explanations with more examples:

Example :

void main( ) {

int a=10, b=5, *p1, *p2;

p1=&a;

p2=&b;

printf("Sum=%d\n",*p1+*p2); /* Same as a + 𝑏 */

printf("Difference=%d\n",*p1-*p2); /* Same as a − b */
printf("Product=%d\n",(*p1)*(*p2)); /* Same as a ∗ b */

printf("Division=%d\n",(*p1)/(*p2)); /* Same as a/b */

Output:

Sum=15

Difference=5

Product=50

Division=2

Some restrictions on pointer arithmetic:

 Address + Address= Invalid Operation


 Address * Address= Invalid Operation
 Address / Address= Invalid Operation
 Address % Address= Invalid Operation
 Bitwise operations are invalid on pointers

Example:

Let p1 and p2 be two pointers pointing to same type of variables, then the following:

p1 + p2 , p1 * p2 , p1 / p2 , p1 % p2 will have error.

Arithmetic operations on pointer variables

If we perform arithmetic operations on pointer variables then we get the following result.

 Address + Number = Address


 Address - Number = Address
 Address ++ = Address
 Address -- = Address
 ++Address = Address
 --Address = Address
 Address - Address= Number

Address + Number = Address

New Address = Old Address + Number * sizeof (datatype)


Example:
1000
int a=8, *pa, *ptr;
a 8 1002
pa=&a; 1004
printf(“pa=%u\t”, pa); pa 1002 1006
1008
ptr=pa+4;
?? 1010

𝑝𝑡𝑟 = 1002 + 4 ∗ 𝑠𝑖𝑧𝑒𝑜𝑓(𝑖𝑛𝑡) 1012


𝑝𝑡𝑟 = 1002 + 4 ∗ 2 = 1010 ptr 1010 1014

printf(“ptr=%u\n”, ptr); 1016


1018
Output:

pa=1002 ptr=1010

Address - Address= Number

 Number = (Address2 – Address1)/sizeof(datatype)


 Here both Address1 and Address2 must be pointers to the same type of
variables.

Example:

float c , d;
XXX 1000
float *pc=&c, *pd=&d; c
XXX 1002
printf(“pc=%u\t”, pc); 1004

printf(“pd=%u\n”, pd); 1006


XXX 1008
printf(“Number=%d\n”, pd-pc); d
XXX 1010
pc 1000 1012
(1008 − 1000)/4 1014
1016
Output:
pd 1008 1018
pc=1000 pd=1008
Number=2 1020
Types Of Pointers

 NULL Pointer
 Dangling Pointer
 Generic Pointer
 Wild Pointer
 Near Pointer
 Far Pointer
 Huge Pointer

1. Null Pointer

 NULL Pointer is a pointer which points to nothing.


 In case, if you don’t have address to be assigned to pointer then you can simply use
NULL
 Pointer which is initialized with NULL value is considered as a NULL pointer.
 NULL is macro constant defined in following header files –
stdio.h, alloc.h , stdlib.h
Example:

#include <stdio.h>

int main()

int *ptr = NULL;

printf("The value of ptr is %u",ptr);

return 0;

Output :

The value of ptr is 0


2. Dangling Pointer

 Dangling pointers arise when an object is deleted or de-allocated, without modifying


the value of the pointer, so that the pointer still points to the memory location of the
de-allocated memory.
 In short, pointer pointing to a non-existing memory location is called dangling
pointer.
Example :
#include<stdlib.h>

void main()

char *ptr = NULL;

.....

.....

char ch;

ptr = &ch;

..... /* dp is now a dangling pointer */

 Character Pointer is declared in the first Step.


 Pointer Variable ‘ptr’ is pointing to Character Variable ‘ch’ declared in the inner
block .
 As character variable is non-visible in outer Block, then Pointer is still pointing to
same invalid memory location in outer block, then Pointer becomes “Dangling”.

3. Generic Pointers
When a variable is declared as being a pointer to type void, it is known as a generic
pointer. Since you cannot have a variable of type void, the pointer will not point to any
data and therefore cannot be dereferenced. It is still a pointer though, to use it you just
have to cast it to another kind of pointer first. Hence the term Generic pointer.
This is very useful when you want a pointer to point to data of different types at different
times.
Example of Generic Pointer

Here is some code using a void pointer:


main()

int i;

char c;

void *the_data;

i = 6;

c = 'a';

the_data = &i;

printf("the_data points to the integer value %d\n", *(int*) the_data);

/* here the_data is apointer type casted from void to int data type.*/

the_data = &c;

printf("the_data now points to the character %c\n", *(char*) the_data);

/* here the_data is a pointer type casted from void to char */

return 0;

4. Wild Pointer
A Pointer in C that has not been initialized till its first use is known as the Wild pointer.
A wild pointer points to some random memory location.
Example :
int main()

{
int *ptr;

/* Ptr is a wild pointer, as it is not initialized Yet */

printf("%d", *ptr);

How can we avoid Wild Pointers?


We can initialize a pointer at the point of declaration wither by the address of some
object/variable or by NULL;
int main()

int val = 5;

int *ptr = &val; /* Initializing pointer */

/* Ptr is not a wild pointer, it is pointing to the address of variable val */

printf("%d", *ptr);

5. Near Pointer

 The pointer which can points only 64KB data segment or segment number 8 is
known as near pointer.
 That is near pointer cannot access beyond the data segment like graphics video
memory, text video memory, etc. Size of near pointer is two byte. With the help of
keyword near, we can make any pointer as near pointer.
Example:

#include<stdio.h>

int main()

int x=25;

int near* ptr;


ptr=&x;

printf(“%d”,sizeof ptr);

return 0;

Output: 2
6. Far Pointer

 The pointer which can point or access whole the residence memory of RAM, i.e.,
which can access all 16 segments is known as far pointer.
 Size of the far pointer is 4 byte or 32 bit.

Example:
#include<stdio.h>

int main()

int x=10;

int far *ptr;

ptr=&x;

printf("%d",sizeof ptr);

return 0;

Output : 4
7. Huge Pointer

 The pointer which can point or access whole the residence memory of RAM i.e.
which can access all 16 segments is known as a huge pointer.
 Size of the far pointer is 4 byte or 32 bit.

Example:
#include<stdio.h>

int main()

char huge * far *p;

printf("%d %d %d",sizeof(p),sizeof(*p),sizeof(**p));

return 0;

Output: 4 4 1
p is the huge pointer, *p is the far pointer and **p is char type data variable.

Double Pointer (Pointer to Pointer)


When a pointer holds the address of another pointer then such type of pointer is known
as pointer-to-pointer or Double Pointer.
The first pointer is used to store the address of the variable. And the second pointer is
used to store the address of the first pointer. That is why they are also known as double
pointers.

How to declare a pointer to pointer?

Declaring Pointer to Pointer is similar to declaring pointer. The difference is we have to


place an additional ‘*’ before the name of pointer.

Syntax:

int **ptr; // declaring double pointers

Example:

int*pr2;

int **pr1;

Here pr1 is a double pointer. There must be two *’s in the declaration of double
pointer.

Let’s understand the concept of double pointer with the help of a diagram:
Variable Name

pr1 pr2 num

66X123X1 XX771230 123 Value

XX661111 66X123X1 XX771230

Variable Address

Figure :Double Pointer Memory Representation

Here pr2 is a pointer holds number 123 and pointer pr1 holds the address of pr2.

Example:

Let n=5, n is located in 1004 and address of p is 1010.

void main( ){

int n=5, *p, **ptr;

p=&n;

ptr=&p;

printf(“n=%d\t”, n);

printf(“p=%u\n”, p);

printf(“Addr of p=%u\t ”, &p);

printf(“ptr=%u\n”, ptr);

printf(“Value=%d\n”, **ptr);
Output:

n=5 p=1004

Addr of p=1010 ptr=1010 Value=5

Precedence of dereferencing operator and increment/decrement operators:

The precedence level of * operator and ++ / -- operators is same and their associativity
is from right to left.
i) x=*ptr++;
The expression *ptr++ is equivalent to *(ptr++) , since these operators associate from
right to left hence ++ operator will be applied to ptr not to * ptr. Here ++ operator is
postfix , so first value of ptr will be used in expression then it will be incremented. Hence
first the integer pointed to by ptr will be dereferenced and assigned to x then ptr will be
incremented. So the above expression is evaluated like
x= *ptr;
ptr=ptr+1;

ii) x= *++ptr; it is evaluated like ptr=ptr+1;


x=*ptr;

iii) x=++*ptr; it is evaluated like * ptr= *ptr+1;


x=*ptr;

iv) x=(*ptr)++; it is evaluated like x= *ptr;


* ptr= *ptr+1;
Simple practice short questions:
1. int a=5;

*pi=&a;

float b=2.2, *pf=&b;

char c=’x’, *pc=&c; pi=1000 pf=4000 pc=5000

Find values of following expressions


i) pi++ ii) pi=pi-3 iii) pi=pi+5 iv) pi—
2. Suppose the value at address 2000 is 25, value at address 2002 is 38. ptr is an
integer pointer that contains address 2000 hence value of *ptr is 25. so evaluate

i) x= *ptr++; ii) x=*++ptr; iii) x= ++*ptr; iv) x= (*ptr)++;

3. int a=5; Let address of a=1000

int *p;

p=&a;

Find:

i) value of p ii) address of a iii) ++p iv) p++ v) --p vi) p-- vii) p

Advantages of Pointers:

 We can dynamically allocate or deallocate space in memory at a run time by


using pointers.
 Using pointers, we can return multiple values from a function.
 We can pass arrays to a function as call by Reference.
 Pointers are used to efficiently access array elements, as array elements are stored
in adjacent memory locations. If we have a pointer pointing to a particular element of
an array, then we can get the address of next element by simply incrementing the
pointer.
 Pointers in C are used to efficiently implement dynamic Data Structures like Queues,
Stacks, Linked Lists, Trees, etc.
 The use of pointers results in the faster execution of the program.

You might also like