Sei sulla pagina 1di 86

Chapter 5

Pointers
Basic Concepts
 In memory, every stored data item occupies one or more
contiguous memory cells (each cell is of 1 byte).
–The number of memory cells required to store a
data item depends on its type (char, int, double, etc.).

 Whenever we declare a variable, the system allocates


memory location(s) to hold the value of the variable.
– Since every byte in memory has a unique address,
this location will also have its own (unique) address.
Introduction
 Consider the declaration,
int i = 3 ;
 This declaration tells the C compiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Store the value 3 at this location.
Contd.
 Consider the statement
int xyz = 50;

– This statement instructs the compiler to allocate a


location for the integer variable xyz, and put the value 50
in that location.
– Suppose that the address location chosen is 1380.

xyz  Variable
50  Value
1380  address
Contd.
 During execution of the program, the system always
associates the name xyz with the address 1380.

– The value 50 can be accessed by using either the name


xyz or the address 1380.
Address vs. Value
 Each memory cell has an address associated with it.

101 102 103 104 105 ……..

…… ……
Address vs. Value
 Each memory cell has an address associated with it.
 Each cell also stores some value.

101 102 103 104 105 ……..

……
50 76 ……
Address vs. Value
 Each memory cell has an address associated with it.
 Each cell also stores some value.
 Don’t confuse the address referring to a memory location
with the value stored in that location.

101 102 103 104 105 ……..

…… 50 76 ……
Values vs. Locations
 Variables name and memory locations, hold values.

1024
Value
32
x
Address
Name
Introduction to Pointers
 First of all, it is variable, just like other variables you
studied.
– so it has type, storage address, value etc.

 A pointer is a variable that holds the memory address of


another variable.

 Since pointer is also a kind of variable , thus pointer itself


will be stored at different memory location.

 Difference: it can only store the address (rather than the


value) of a data item.
Pointer Declarations
 Like any variable, you must declare a pointer before using it
to store any variable address.
 A pointer is just a C variable whose value is the address of
another variable!
• General form:
data_type *pointer_name;
 Three things are specified in the above declaration:
• The asterisk (*) tells that the variable pointer_name
is a pointer variable.
• pointer_name needs a memory location.
• pointer_name points to a variable of type data_type.

pointer_name Variable
(data_type)
(data_type)
Cont..

 Declaration of pointer
data_type * variable_name;
int * ptr;

 After declaring a pointer like:


int *ptr;
ptr doesn’t actually point to anything yet. We can either:
– make it point to something that already exists or
– allocate room in memory for something new that it will
point to.
Pointer Declarations
 Example:
int *count;

float *speed;

int * xp ;

double *salary;
Cont..
int x;
Pointer to int
int * xp ;

int *ip; // pointer to an integer


double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch; // pointer to a character
Pointer Initialization
 Declaring a pointer just allocates space to hold the pointer
– it does not allocate something to be pointed to!
 Local variables in C are not initialized by default, they may
contain anything.

 Once a pointer variable has been declared, it can be made


to point to a variable using an assignment statement like:

int *p, xyz;


:
p = &xyz;
– This is called pointer initialization.
Pointer variable can be initialized with NULL or 0 value.
Cont..
int x=32;
Pointer to int
int * xp ;
xp = &x ;
Address of X
Cont..
int x=32;
Pointer to int
int * xp ;
xp = &x ; X 32
Address of X 1024

xp 1024
2868
Cont….
 Since a pointer is a variable, its value is also stored in
some memory location.
 Example- int *p, xyz=50;
p=&xyz;
 But remember that p is not an ordinary variable like any
other integer variable. It is a variable that contains the address
of other variable (xyz in this case). Since p is a variable the
compiler must provide it space in the memory. The following
memory map would illustrate the contents of p and xyz.

50 1380
xyz p
1380 2545
Cont….

Variable Value Address

xyz 50 1380
p 1380 2545
Simple Pointer Example:
#include<stdio.h>
int main()
{
int a = 3;
int *ptr;
ptr = &a;
printf(“%u\n”, &a);
printf(“%u\n”, ptr);
return 0;
}

Note- to avoid the warning while printing address of any variable


use %p format specifier (it gives output in hexadecimal).
Explanation of Example :

Point Variable 'a' Variable 'ptr'

Name of Variable a ptr

Type of Value that it


Integer Address of Integer 'a'
holds

Value Stored 3 2001

Address of Variable 2001 (Assumption) 4001 (Assumption)


C pointer address operator (&)
 The address of a variable can be determined using the ‘&’
operator.
– The operator ‘&’ immediately preceding a variable
returns the address of the variable.
&n - It gives an address of variable n
 Example:
p = &xyz;
– The address of xyz (1380) is assigned to p.
 The ‘&’ operator can be used only with a simple variable or
an array element.
&distance
&x[0]
&x[i-2]
Contd.
 Following usages are illegal:

&235
&(‘b’)
• with constant.

&(a+b)
• with expression.
Example
#include <stdio.h> Address of A: 3221224908
main() Address of B: 3221224904
{ Address of C: 3221224900
int a; Address of D: 3221224892
float b, c; Address of ch: 3221224891
double d;
char ch;
a = 10; b = 2.5; c = 12.36; d = 12345.66; ch = ‘A’;
printf (“%d is stored in location %u \n”, a, &a) ;
printf (“%f is stored in location %u \n”, b, &b) ;
printf (“%f is stored in location %u \n”, c, &c) ;
printf (“%lf is stored in location %u \n”, d, &d) ;
printf (“%c is stored in location %u \n”, ch, &ch) ;
}
Output:
10 is stored in location 3221224908
2.500000 is stored in location 3221224904
12.360000 is stored in location 3221224900
12345.660000 is stored in location 3221224892
A is stored in location 3221224891

Note- In order to print the variable we simply use name of variable


while to print the address of the variable we use ampersand (&) along
with %u (%p).
Understanding address operator
#include<stdio.h>
int main()
{
int i = 5;
int *ptr;

ptr = &i;

printf("\nAddress of i : %u",&i);
printf("\nValue of ptr is : %u",ptr);

return 0;
}
Understanding address operator
After declaration memory map will be like this –

int i = 5;
int *ptr;

after Assigning the address of variable to pointer , i.e after the


execution of this statement –

ptr = &i;
Things to Remember
 Pointer variables must always point to a data item of the
same type.

float x;
int *p;
gives warning and will result in erroneous output
:
p = &x;
 Assigning an absolute address to a pointer variable is
prohibited. (except NULL or 0 value no other constant value
can be assigned).
 int *p = NULL; int*p= 0; // allowed

int *count;
:
count = 1268;// can’t be assigned
How much memory space does a pointer take
#include <stdio.h>
int main()
{
int a = 5;

int* int_pointer; // an integer pointer


float* float_pointer; //a float pointer
char* char_pointer; //a character pointer
printf("size of an int pointer = %d\n", sizeof(int_pointer));
printf("size of an float pointer = %d\n", sizeof(float_pointer));
printf("size of an char pointer = %d\n", sizeof(char_pointer));

return 0;
}
Accessing a Variable Through its Pointer
 This is done by using unary operator * that returns the
value of the variable located at the address specified by its
operand.

 Once a pointer has been assigned the address of a


variable, the value of that variable can be accessed using
the indirection operator (*).

int a, b;
int *p;
: b = a;
p = &a;
b = *p; // assign value of a in
b
Accessing a Variable Through its Pointer
 Asterisk Operator is also called as value at address
operator.

 When used with pointer variable, it refers to variable


being pointed to, this is called as Dereferencing of
Pointers

 Dereferencing Operation is performed to access or


manipulate data contained in memory location pointed to
by a pointer.

 Any operation performed on the de-referenced


pointer directly affects the value of variable it pointes to.
Accessing a Variable Through its Pointer
int num = 50 , x ;
int *ptr ;

ptr = &num; // Stores address of num in ptr

x = *ptr; // Put value at ptr in x

Variable Value in it
num 50
&num 1002
ptr 1002
*ptr 50
Accessing a Variable Through its Pointer
int x; Pointer to int
int * p ;
1024: 32
p= &x; X
Address of X
1024
…..
(x == *p) True p
(p == &x) True
p means Address of variable x
*p means
i.e. content of address of variable x
i.e. data of x itself
Accessing a Variable Through its Pointer
int x;
Pointer to int
int * xp ;
xp = &x ; X 0
Address of X 1024

xp 1024

xp – means address of x
*xp- means value at x
*xp = 0; /* Assign 0 to x */
Accessing a Variable Through its Pointer
int x;
Pointer to int
int * xp ;
xp = &x ; X 1
Address of X 1024

xp 1024

xp – means address of int x


*xp = *xp + 1; // Add 1 to x
Example
#include <stdio.h>
int main ()
{
int var = 20; // variable declaration
int *ip; // pointer variable declaration
ip = &var; // store address of var in pointer variable

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

/* address stored in pointer variable */


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

/* access the value of variable using the pointer */


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

return 0;
}
Example
#include <stdio.h>
void main()
{ Equivalent
int a, b;
int c = 5;
int *p;
a = 4 * (c + 5) ;
p = &c;
b = 4 * (*p + 5) ;
printf (“a=%d b=%d \n”, a, b);
}
Output-
a=40 b= 40
void main()
{
int i = 3 ;
int *j ;
j = &i ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nAddress of i = %u", j ) ;
printf ( "\nAddress of j = %u", &j ) ;
printf ( "\nValue of j = %u", j ) ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *j ) ;
}
Pointer arithmetic
 Like other variables, pointer variables can be used in
expressions.

 If p1 and p2 are two pointers, the following statements


are valid:
sum = *p1 + *p2;
prod = *p1 * *p2;
prod = (*p1) * (*p2);
*p1 = *p1 + 2;
x = *p1 / *p2 + 5;
Pointer invalid operations
 Addition of two addresses or pointer variables.
 Multiplying two addresses.
 Division of two addresses.
 Modulo operation on pointer.
 Cannot perform bitwise AND,OR,XOR operations on pointer.
 Cannot perform NOT operation or negation operation.
 Address + Address = Illegal
 Address * Address = Illegal
 Address / Address = Illegal
 Address % Address = Illegal
 Address & Address = Illegal
 Address | Address = Illegal
 Address ^ Address = Illegal
 ~Address = Illegal
Contd.
 What are allowed in C?
– Add an integer to a pointer.
p1 = p2 + 2;
– Subtract an integer from a pointer.
p1 = p2 - 2;
– Subtract one pointer from another (related).
• If p1 and p2 are both pointers to the same array,
then p2– p1 gives the number of elements between p1
and p2.
 2 pointers can be incremented , decremented and
compared (using relational operators).
p1++;
p1>p2, p1= = p2 and p1!= p2 (p1 and p2 points to
objects of same data type)

 What are not allowed?


– Add two pointers.
p1 = p1 + p2;
– Multiply / divide a pointer in an expression.
p1 = p2 / 5;
p1 = p1 *p2 ;
p1= p2/p1;
 Adding integer value with Pointer
 In order to compute the final value we need to use following
formulae :
 final value = (initial_address) + (number * (sizeof(data_type)))
 Example;
int *ptr , n;
ptr = &n ;
ptr = ptr + 3;
 Let initial value of ptr is 1000, sizeof int is 2.
 New value of ptr will be 1006
 Subtracting integer value from pointer

 Suppose we have subtracted “n” from pointer of any data type


having initial addess as “init_address” then after subtraction
we can write –
 ptr = initial_address - n * (sizeof(data_type))
Incrementing/Decrementing a Pointer
 Incrementing Pointer is generally used in array because we have
contiguous memory in array and we know the contents of next
memory location.
 Incrementing Pointer Variable Depends Upon data type of the Pointer
variable
 new value = current address + size_of(data type of pointer)

If p1 is an integer pointer, then


p1++
will increment the value of p1 by 4 (Assuming sizeof(int) is 4).

 The same considerations apply to decrementing a pointer, which


decreases its value by the number of bytes of its data type.
 Note to Remember : Increment and Decrement Operations on
pointer should be used when we have Continues memory (in Array).
Incrementing a Pointer

Considering
sizeof(int) as 2

Next Address
Older Address stored in
Data Type stored in pointer after
pointer incrementing
(ptr++)
int 1000 1004
float 1000 1008
char 1000 1001
Decrementing a Pointer

Next Address
stored in pointer
Older Address
Data Type after
stored in pointer
decrementing
(ptr–)
int 1000 0996
float 1000 0994
char 1000 0999
Rules of Pointer Operations
 Pointer Variable Can be Assigned the address of another
Variable
int num = 10;
int *ptr;
ptr = &num;
 Pointer Variable Can be Assigned the value of another Pointer
Variable
int *sptr,*tptr, num=2;;
sptr = &num;
tptr = sptr;
 Pointer Variable Can be initialized with zero or NULL value.
int *sptr,*tptr;
sptr = 0;
tptr = NULL;
Rules of Pointer Operations
 Pre/Post fix Increment/Decrement Operation Can be Performed
on Pointer variable
int arr[20];
int *ptr;
ptr = &arr;
ptr++;
 Integer value can be added or Subtracted from Pointer variable
int arr[20];
int *ptr;
ptr = &arr;
ptr = ptr + 2; //arr[2] will be accessed
Rules of Pointer Operations
 A Value cannot be assigned to arbitrary address
int *ptr;
ptr = &100; //Illegal
 Pointer Variable cannot be multiplied by Constant
int *ptr;
ptr = ptr * 6; //Illegal
 2 Pointer variables cannot be added
int*p, *q;
p= p+q;

 When two Pointer points to same array then one Pointer


variable can be Subtracted from another
 Two Pointers pointing to objects of same data type then they
can be compared using the Relational Operator
Passing Pointers to a Function
 When we pass the address to a function, the parameters
receiving the addresses should be pointers.
 The process of calling a function using pointers to pass the
addresses of variables is known as ‘call by reference’ (or by
address or by location or pass by pointers).
 The function which is called by ‘reference’ can change the
value of the variable used in the call.
– Allows data items within the calling program to be accessed
by the function, altered, and then returned to the calling
program in altered form.
 Normally, arguments are passed to a function by value.
– The data items are copied to the function.
– Changes are not reflected in the calling program.
Example: passing arguments by value
#include <stdio.h>
swap(int, int);
main()
{
int a, b; Output
a = 5; b = 20; a=5, b=20
swap (a, b);
printf (“\n a=%d, b=%d”, a, b);
Parameters
}
passed by
void swap (int x, int y)
value, so
{
changes done
int t;
on copy, not
t = x;
returned to
x = y;
calling
y = t;
function
}
Example: passing arguments by reference
#include <stdio.h>
swap(int*, int*);
main()
{
int a, b; Output
a = 5; b = 20; a=20, b=5
swap (&a, &b);
printf (“\n a=%d, b=%d”, a, b);
Parameters
}
passed by
void swap (int *x, int *y)
address,
{
changes done
int t;
on the value
t = *x;
stored at that
*x = *y;
address
*y = t;
}
Example: passing arguments by reference
void change(int*, int*);
main()
{
int x;
x = 20; Output
change(&x); x=30
printf (“x=%d”, x);
}
When a function change
void change (int *p)
is called, the address of
{
the variable x not its
*p= *p +10;
value is passed into the
}
function change.
Dereferenced pointer is
used in function body,
Pass by value and reference
(a) If we want that the value of an actual argument should not get
changed in the function being called, pass the actual argument
by value.

(b) If we want that the value of an actual argument should get


changed in the function being called, pass the actual
argument by reference.

(c) If a function is to be made to return more than one value at a


time then return these values indirectly by using a call by
reference.
Returning multiple values from a function
 Return statement can return only one value
 What if we want to return more than one value?

 Use pointers
• Return one value as usual with a return statement
• For other return values, pass the address of a variable in
which the value is to be returned

 Using a call by reference intelligently, we can make a function


return more than one value at a time, which is not possible
ordinarily.
Example:

void areaperi ( int , float *, float * );


void main( )
{
int radius=0; float area=0.0, perimeter= 0.0 ;
printf ( "\n Enter radius of a circle " ) ;
scanf ( "%d", &radius ) ;
areaperi ( radius, &area, &perimeter ) ;
printf ( "Area = %f", area ) ;
printf ( "\n Perimeter = %f", perimeter ) ;
}
void areaperi ( int r, float *a, float *p )
{
*a = 3.14 * r * r ;
*p = 2 * 3.14 * r ;
}
Pointers and Arrays
 When an array is declared,
– The compiler allocates a base address and sufficient
amount of storage to contain all the elements of the array
in contiguous memory locations.
– The base address is the location of the first element
(index 0) of the array.
– The compiler also defines the array name as a constant
pointer to the first element.
Example:
main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i ;
for ( i = 0 ; i <= 5 ; i++ )
{
printf ( "\nelement no. %d ", i ) ;
printf ( "address = %u", &num[i] ) ;
}
}
Pointers and Arrays
 Recall that an array name is really a constant pointer to the
first element in the array.
 We know that array name without subscript points to first
element in an array

 Example : One dimensional array


 int a[10];
Here a , a[0] both are identical

 Example : Two dimensional Array


 int a[10][10];
Here a , a[0][0] both are identical
Contd.
■ Therefore, if x is a one dimensional array, then the address of the first
array element can be expressed as either &x[0] or simply as x.

■ Moreover, the address of the second array element can be written as


either &x[1] or as (x + 1), and so on.
■ In general, the address of array element i can be expressed as either
&x[i] or as (x + i).

■ Thus we have two different ways to write the address of any array
element:
■ We can write the actual array element, preceded by an ampersand; or
we can write an expression in which the subscript is added to the
array name.
Hence, the expression (x + i) is a symbolic representation for an
address specification rather than an arithmetic expression.
x[i] and *(x + i) both represent the contents of that address, i.e., the
value of the ith element of x.
Pointers and Arrays
 Consider the declaration:
 int x[5] = {1, 2, 3, 4, 5};
 Suppose that each integer requires 4 bytes
 Compiler allocates a contiguous storage of size 5x4 = 20
bytes
 Suppose the starting address of that storage is 2500

Element Value Address


x[0] 1 2500
x[1] 2 2504
x[2] 3 2508
x[3] 4 2512
x[4] 5 2516
Contd.
■ An array name is an address, or pointer, that is fixed.
■ It is a CONSTANT pointer to the first element.
■ The array name x is the starting address of the array
■ Both x and &x[0] have the value 2500
■ x is a constant pointer, so cannot be changed
■ x = 2500, x++, x += 2 are all illegal
■ If int *p is declared, then
p = x; and p = &x[0]; are equivalent
■ We can access successive values of x by using p++ or p--
to move from one element to another
Contd.
 Relationship between p and x:
p = &x[0] = x = 2500
p+1 = &x[1] = 2504
p+2 = &x[2] = 2508
p+3 = &x[3] = 2512
p+4 = &x[4] = 2516

 C knows the type of each element in array x, so knows how


many bytes to move the pointer to get to the next element

*(p+i) gives the value of x[i] (ith element of an array)


Pointer pointing to the array of elements
int x[ ] = {1,2,3,4,5};
int *ptr, i ;
ptr = x;
for(i=0;i<5;i++)
{
printf(“\nAddress : %u", &x[i]); //display array address

printf(“\nAddress : %u", (ptr +i));

printf(“\nElement : %d", x[i]); // display array element

printf(“\nElement : %d",*(ptr +i));


}
Example:
void main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i, *j ;
j = &num[0] ; /* assign address of zeroth element */
for ( i = 0 ; i <= 5 ; i++ )
{
printf ( "\naddress = %u ", j ) ;
printf ( "element = %d", *j ) ;
j++ ; /* increment pointer to point to next location */
}
}
The output of this program would be:
address = 65512 element = 24
address = 65514 element = 34
address = 65516 element = 12
address = 65518 element = 44
address = 65520 element = 56
address = 65522 element = 17
Example:
void main( )
{
int arr[ ] = { 10, 20, 30, 45, 67, 56, 74 } ;
int *i, *j ;
i = &arr[1] ;
j = &arr[5] ;
printf ( "%d %d", j - i, *j - *i ) ;
}
Example:
void main( )
{
int arr[ ] = { 10, 20, 36, 72, 45, 36 } ;
int *j, *k ;
j = &arr [ 4 ] ;
k = ( arr + 4 ) ;
if ( j == k )
printf ( "The two pointers point to the same
location" ) ;
else
printf ( "The two pointers do not point to the same
location" ) ;
}
Passing Arrays as Pointers
 Both the forms below are fine in the function body, as arrays
are passed by passing the address of the first element.
Passing an Entire Array to a Function
void display(int [ ],int );
main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
display ( &num[0], 6 ) ; // num=&num[0]
}
void display ( int j[ ], int n )
{
int i ;
for ( i = 0 ; i <= n - 1 ; i++ )
{
printf ( "\nelement = %d", j[i] ) ;
}
}
Passing an Entire Array to a Function
void display ( int *, int );
main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
display ( &num[0], 6 ) ;
}
void display ( int *j, int n )
{
int i ;
for ( i = 0 ; i <= n - 1 ; i++ )
{
printf ( "\n element = %d", *j ) ;
j++ ; /* increment pointer to point to next element */
}
}
Example: Returning max and min of an array
 Both values returned through pointers (could have returned one
of them through return statement also)
Strings
• 1-d arrays of type char
• By convention, a string in C is terminated by the end-of-
string sentinel ‘\0’ (null character)
• char s[21] - can have variable length string delimited
with \0
• Max length of the string that can be stored is 20 as the size
must include storage needed for the ‘\0’
• String constant : “Hello”
char str[ ] = "Hello" ;

• str is a character array of size 6


Pointers and Strings
void main( )
{
char name[ ] = “ABCD" ;
char *ptr ;
ptr = name ; /* store base address of string */
while ( *ptr != ‘\0' )
{
printf ( "%c", *ptr ) ;
ptr++ ;
}
}
String Constant

• A string constant is treated as a pointer


• Its value is the base address of the string
char *p = “abc”;

p
a b c \0

printf (“%s %s\n”,p,p+1); /* abc bc is printed */


Pointers and Strings

#include<stdio.h>

int main()
{

char *name=“ABC";

printf("Name is %s \n", name);

}
Pointers and Strings
#include<stdio.h>

int main()
{
int i;

char arr[4] = “FCP";


char *ptr = &arr;

for(i=0;i<4;i++)
printf(“………. of Character %d : %......\n” ,i,(ptr +i));

return 0;
}
Pointers and Strings
#include<stdio.h>

int main()
{
int i;

char arr[4] = “FCP";


char *ptr = &arr;

for(i=0;i<4;i++)
printf("Address of Character %d : %u\n“ ,i,(ptr +i));

return 0;
}
Differences : string(char array) & char pointer

char *p = “abcde”; char s[ ] = “abcde”;


The compiler allocates  char s[ ] = {‘a’,’b’,’c’,’d’,’e’.’\0’};
space for p, puts the
The compiler allocates 6 bytes
string constant “abcde”
of memory for the array s
in memory somewhere
which are initialized with the
else, initializes p with
6 characters
the base address of
the string constant
p
S a b c d e\
a b c d e \0 0
Contd..
• char str[ ] = "Hello" ;
• char *p = "Hello" ;
 difference in usage of these two forms
• we cannot assign a string to another, whereas, we
can assign a char pointer to another char pointer.

main( )
{
char str1[ ] = "Hello" ;
char str2[10] ;
char *s = "Good Morning" ;
char *q ;
str2 = str1 ; /* error */
q = s ; /* works */
}
Contd..
 Also, once a string has been defined it cannot be initialized
to another set of characters. Unlike strings, such an
operation is perfectly valid with char pointers.

main( )
{
char str1[ ] = "Hello" ;
char *p = "Hello" ;
str1 = "Bye" ; /* error */
p = "Bye" ; /* works */
}
Void Pointer: Introduction
 Suppose we have to declare integer pointer,character pointer
and float pointer then we need to declare 3 pointer variables.
 Instead of declaring different types of pointer variable it is
feasible to declare single pointer variable which can act as
integer pointer,character pointer and float pointer.

Void Pointer Basics :


 In C General Purpose Pointer is called as void Pointer.
 It does not have any data type associated with it.
 It can store address of any type of variable.
 A void pointer is a C convention for a raw address.
 The compiler has no idea what type of object a void Pointer
really points to ?
Contd….
 Declaration of Void Pointer :

void * pointer_name;

 Void Pointer Example :

void *ptr; // ptr is declared as void pointer


char cnum;
int inum;
float fnum;
ptr = &cnum; // ptr has address of character data
ptr = &inum; // ptr has address of integer data
ptr = &fnum; // ptr has address of float data
Contd…
 Void pointer declaration is shown in above program.
 We have declared 3 variables of integer, character and
float type.
 When we assign address of integer variable to the void
pointer, pointer will become Integer Pointer.
 When we assign address of Character data type variable
to void pointer it will become Character Pointer.
 Similarly we can assign address of any data type to the
void pointer.
 It is capable of storing address of any data type
Contd…
#include<stdio.h>
int main()
{
int a=3;
float b=3.4;
void *vptr; // void pointer can point to any data type
vptr=&a;
printf("Value of ‘a’ with void pointer=%d\n", *(int *)vptr); /*type
casting of void to integer*/
*(int *)vptr=12;
printf("Value of ‘a’ with void pointer=%d after updation\n", *(int
*)vptr);
vptr=&b;
printf("Value of b with void pointer=%f\n", *(float *)vptr); /* type
casting of void to float*/

Potrebbero piacerti anche