0% found this document useful (0 votes)
11 views25 pages

Unit 1

The document provides an overview of pointers in C programming, explaining their definition, features, and usage. It covers how to declare, initialize, and access variables through pointers, as well as concepts like dangling pointers, null pointers, and pointer arithmetic. Additionally, it includes examples and syntax for various pointer operations, emphasizing their efficiency in memory management and data manipulation.

Uploaded by

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

Unit 1

The document provides an overview of pointers in C programming, explaining their definition, features, and usage. It covers how to declare, initialize, and access variables through pointers, as well as concepts like dangling pointers, null pointers, and pointer arithmetic. Additionally, it includes examples and syntax for various pointer operations, emphasizing their efficiency in memory management and data manipulation.

Uploaded by

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

Data Structures

POINTERS
When variables are declared, memory is allocated to each variable. C provides data
manipulation with addresses of variables therefore execution time is reduced. Such concept is
possible with special data type called pointer. The basic data types in c language are int, float, char,
double and void and so on. Pointer is a special data type which is derived from these basic
datatypes.so pointers is called derived data type. Pointer is a data object that refers to a memory
location, which is an address. Thus, a pointer variable may contain address of another variable (or)
any valid address in the computer memory.
Pointer: A Variable which holds address of another variable is called a pointer variable. In
other words, pointer variable which holds pointer value (i.e., address of a variable).
Features of pointers:
Pointers save the memory space.
Execution time with pointers is faster because data is manipulated with the addresses ,that
is direct access to memory location.
The memory is accessed efficiently with the pointers. the pointer assign the memory
space and it also releases .dynamically memory is allocated
Pointers are useful for representing two and multi-dimensional arrays
Consider the Declaration:
Syntax: int x=3;
The above declaration tells the compiler to
Reserve the space in memory to hold the integer value
Associate the name x with this memory location
Store the value 3 at this location.
We may represent x’s location in the memory by the following memory map

Accessing the address of a variable: we can access the address of a variable by using &.The &
immediately preceding a variable associated with it.
Syntax: p=&x;
Example: We can print the address through the following program
#include<stdio.h>
main()
{
int x=3;
Printf(“\n address of x is %u”,&x);
Printf(“\n value of I is %d”,x);
CSE DEPT. Page 1
Data Structures

}
Output: address of x is 64825
value of x is 3
The ‘&’ operator used in the first printf statement, which is called address of operator. The ‘&x’
returns the address of variable x.
For example, if x is a variable and address of x is stored in a variable p as shown below.
p=&x;
Here the variable p is called a pointer variable. The memory organization after executing the above
atatement is shown below
Physical representation:

Variable Address Memory Locations

0000 65534
p 5

5534 300
x 6


Physical representation
The address of a variable x which is 65534 is assigned to variable p. so, even though address
of p is 50,000 (pointer value), the value stored in that location is 65534.
Since p is a variable which contains address of a variable x, so the variable p is called pointer
variable.

CSE DEPT. Page 2


Data Structures

Logical representation:

300

p x
In the logical representation, the variable p points to the variable x. So, we say that the variable p
points to x and hence the name pointer.
If we use the statement: p = &x;
The variable p contains the address of variable x.
A Pointer variable should contain only the address (i.e, pointer value)
The difference between pointer value and value stored in memory location is pointer value is 50,000
and value stored in memory location is 65534.
pointer declaration:
In a C language all the variables should be declared before they are used. Pointer variables also should
be declared before they are used. The syntax to declare a pointer variable is
Syntax: type * identifier
Here, identifier –it is name given to the pointer variable.
* -tells that the identifier is a pointer variable
Type- it can be any data type such as int, float, char etc., it can be derived (user
defined data type also)
Example: int *p;
The above declaration can be read as “p is a pointer to integer variable” that is p is a pointer
variable and can hold the address of another variable of type int. In the declaration the position of *
is immaterial, For example the following declarations are same;
Example: int *pa;
int * pa;
int* pa;
consider the multiple declarations
Example: int* pa, pb, pc;
Only pa is a pointer variable, whereas the variable pb and pc are ordinary integer variables. For better
readability, the above declaration can be written as shown below:
int *pa;
int pb;
int pc;
Initializing a pointer variable: Initialization of a pointer variable is the process of assigning the
address of a variable to a pointer variable. The initialization of a pointer variable can be done using
following three steps.
1. Declare a data variable
2. Declare a pointer variable
CSE DEPT. Page 3
Data Structures

3. Assign address of a data variable to a pointer variable using & operator and
assignment operator.
Example: int x; (1) step
int *p; (2) step
p = &x; (3) step
Here, the variable x is declared as integer variable. Since p is a pointer variable of type
integer, it should contain address of integer variable. So, using the below statement.
p = &x
Example: int x = 10, y = 20, z = 30;
int *p;
p = &x;
p = &y;
p = &z; x
10

p
20
y

30
z
Here, the pointer variable p points to different memory locations by storing the address of different
variables. Thus, the same pointer can be pointed to different data variables.
Example: int x=10;
Int *p,*q,*r;
P=&x;
Q=&x;
R=&x;
p
10

x
20
q

30
r
accessing variables through its pointers: The following steps to be followed while accessing the
variables using pointers.
Declare a data variable int a,n;
Declare a pointer variable int *p;
Initialize a pointer variable p=&a;

How to access the value of variable using pointer: once a pointer has been assigned the address of

CSE DEPT. Page 4


Data Structures

a variable, the question remains as to how to access the value of the variable using the pointer. This
can be done by using pointer variable and unary operator *.This operator is called indirection (or)
value at address (or) dereferencing operator.
n=*p;
Example: int x=100,y;
Int *p;
P=&x; /*address of x is stored in pointer variable p */
Y=*p; /*p has address of x, the value of variable x is, i.e 100 is copied into y*/
Note: By specifying *p, the value of the variable whose address is stored in p can be accessed. Here
p should be a pointer variable.
Step 1:
Declaration Variables Address

int *p; p 5000


Garbage
int *q; q 5002
Values
int *r; r 5004

int x = 10; x 5006

After declaration, the pointer variables p, q & r does not contain valid addresses and hence
are called dangling pointers.
Step 2:

Initialization Variables Address


50 06
p = &x; p 5000

q = &x; q 5002 50 06

50 06
r = &x; r 5004

x 5006 10
After executing these statements, the pointer variables p, q and r contains the address of integer
variable x.
Step 3: Accessing the item 10:
pintf(“&p = %u, p = %u, *p = %d \n”, &p, p, *p);
printf( “&q = %u, q = %u, *q = %d\n”, &q, q, *q);
printf(“&r = %u, r = %u, *r = %d\n”, &r, r, *r);
output: &p = 5000, p = 5006, *p = 10
&q = 5002, q = 5006, *q = 10
&r = 5004, r = 5006, *r = 10
Dangling Pointer: A pointer variable which does not contain a valid address is called dangling
pointer.
CSE DEPT. Page 5
Data Structures

Consider the following declaration.


int *p;
This indicates that p is a pointer variable and the corresponding memory location should
contain address of an integer variable. But the declaration will not initialize the memory location and
memory contains garbage value as shown below:
p garbage value
Here, the pointer variable p does not contain a valid address and we say that it is a dangling
pointer.
Consider the following declarations assume that all are global variables
int *pi;
float *pf;
char *pc;
All global variables are initialized by the compiler during compilation. The pointer variables are
initialized to null indicating that they do not point to any memory locations as shown below.

null
pi

null
pf

null
pc
Consider the following declarations assume that all are local variables
int *pi;
float *pf;
char *pc;
The global variables are not initialized by the compiler during compilation. This is because; the local
variables are created and used only during runtime. The pointer variables are also will not be
initialized hence the memory contains some garbage values

Garbage value
pi

Garbage value
pf

Garbage value
pc
The data can be accessed using pointers after declaration and initialization as follows:
Example: #include<stdio.h>

CSE DEPT. Page 6


Data Structures

main()
{
int i=3;
int *j;
j=&i;
printf(“address of I is %d”,&i);
printf(“address of I is %d”,j);
printf(“address of j is %d”,&j);
printf(“value of j is %d”,j);
printf(“value of I is %d”,i);
printf(“value of I is %d”,*(&i));
printf(“value of I is %d”,*j);
}
The concept of pointer can be further extended. We know that pointer is a variable which holds the
address of another variable. Now this variable itself contains the address of another pointer. Thus we
can have a pointer, which contains another pointers address.
Example: #include<stdio.h>
main()
{
int i=3;
int *j;
int **k;
j=&i;
k=&j;
printf(“address of I is %d”,&i);
printf(“address of I is %d”,j);
printf(“address of j is %d”,*k);
printf(“value of j is %d”,&j);
printf(“value of j is %d”,k);
printf(“value of k is %d”,&k);
printf(“value of I is %d”,i);
printf(“value of I is %d”,*(&i));
printf(“value of I is %d”,*j);
printf(“value of I is %d”,**k);
printf(“value of j is %d”,j);
printf(“value of k is %d”,k);
}
Null Pointer: A Null pointer is defined as a special pointer value that points to nowhere in the
memory. If it is too early in the code to assign a value to the pointer, then it is better to assign NULL
(i.e, \0 or 0) to the pointer.
Example: #include <stdio.h>
int *p = NULL;
Here the pointer variable p is a NULL pointer. This indicates that the pointer variable p does not
point to any part of the memory. The value for NULL is defined in the header file “stdio.h”.
The programmer can access the data using the pointer variable p if and only it does not contain NULL.
The error condition can be checked using the following statement:

CSE DEPT. Page 7


Data Structures

if ( p == NULL)
printf(“„ p does not point to any memory”);
else
printf(“Access the value of p \n”);
Example: int *x; int y;
x = y // error.
The value of data variable cannot be assigned to a pointer variable. So the statement x = y; results
an error. The correct statement is x = &y;
Example: Write a program to read two numbers and then add two numbers using pointers.
#include <stdio.h>
void main ( )
{
int a , b, sum; int *p, *q;
p = &a;
q = &b;
scanf (“%d %d”, &a, &b);
sum = *p + *q;
printf („”sum = %d\n”, sum);
}
Input: 10 20
Output: 30
Pointers and expressions: pointer variables can be used for accessing values in arithmetic
expressions.
Example: (*p1)*(*p2)
Sum=sum+(*p1);
Arithmetic operations on pointer variables: Arithmetic operations on pointer variables are also
possible.
Increment and decrement of pointers: It is possible to increment and decrement pointer variables
using ++ and – operators respectively.
A pointer expression may be preceded by and followed by ++ (or) --.in such cases the operators
&,*,and,++(or)—are involved
While evaluating these expressions, it is very important to remember the operator precedence
and associativity of the operators. The operators &,*,++,and,-- have same precedence level and
the evaluation is carried out from right to left.
Example: int *p,x=20;
P=&x;
++ *p;
*p ++;
Example: #include<stdio.h>
main()

CSE DEPT. Page 8


Data Structures

{
int *p,*q,*r;
int a=10,b=20,c=30;
p=&a;
q=&b;
r=&c;
printf(“%u%u%u”,p,q,r);
printf(“%d%d%d”,*p,*q,*r);
printf(“%u%u%u”,++p,++q,++r);
}
Output: 100 200 300
10 20 30
102 202 302
Scale factor length: when we increment a pointer its value is incremented by the length of the
data type it is pointing is called scale factor.
Example: Assume p1 is an integer pointer with initial value of 2800, then after executing the p1++
statement, the value of p1 will be 2802, and not 2801.
Example: Assume p1 is a character pointer with initial value of 2800, then after executing the p1++
statement, the value of p1 will be 2801.
Example: Assume p1 is a float pointer with initial value of 2800, then after executing the p1++
statement, the value of p1 will be 2804.
Example: Assume p1 is a double pointer with initial value of 2800, then after executing the p1++
statement, the value of p1 will be 2808.
Rules for pointer operations:
A pointer variable can be assigned to another pointer variable, if both are pointing to the
same data type.
A pointer variable can be assigned a NULL value.
A pointer variable cannot be multiplied or divided by a constant.
Example: p*3 or p/3 where p is a pointer variable
One pointer variable can be subtracted torn another provided both winters points to Elements
on same away.
C allows us to add integers to or subtract integers from pointers.
Example: p1+4, p2-2, p1-p2 If both p1, p2 are pointers to same way then p2-p1 gives the
number of elements between p1,p2
Pointer variable can be incremented or decremented p++ & p- -
When a pointer to an integer is incremented by one and if 2 bytes are used for int, the address
is incremented by 2.such scale factors necessary for the pointer arithmetic are taken care by the
compiler.

CSE DEPT. Page 9


Data Structures

Pointers and other operations: Operations performed on pointers is


Adding an integer to a pointer.
Subtracting an integer from pointer
Subtracting two pointers
Comparing two pointers
Adding an integer to a pointer: Here, one operand is a pointer and other operand is an integer.
Consider the following declaration:
int a[5] = {10,20,30,40,50};
int *p1, *p2;
p1 = a;
p2 = a;
the various valid and invalid statements are
p1 = p1 + 1; valid
p1 = p1 + 3; valid
p1 + p2; invalid: two pointers cannot be added
p1++; valid
Example: Display array elements using pointers:
#include<stdio.h>
void main ( )
{
int a [ ] = { 10,20,30,40,50};
int *p;
int i;
p = a;
for (i = 0; i<=4; i++)
{
printf(“%d\n”, *p);
p++;
}
}
Example: Sum of n numbers using pointers
#include<stdio.h>
void main ( )
{
int a [ ] = { 10,20,30,40,50}; int *p;
int i, sum; p=a;
sum = 0;
for (i = 0; i<=4; i++)
{
sum = sum + *p;
p++;
}
printf(“sum = %d”, sum);
}
Subtracting an integer from a pointer: Subtracting can be performed when first operand is a pointer
and the second operand is an integer.

CSE DEPT. Page 10


Data Structures

Example: int a[5] = {10,20,30,40,50};


int *p1;
p1= &a[4];
the various valid and invalid statements are
p1= p1 - 1; it is valid
p1= p1 - 3; it is valid
p1--; it is valid
--p1; it is valid
p1 = 1 – p1 it is invalid (illegal pointer subtraction)
Example: #include<stdio.h>
main()
{
int a[5]={10,20,30,40,50};
int *p;
p=&a[4];
for(i=0;i<5;i++)
{
printf(“%d”,*p);
p--;
}
}
Output: 50 40 30 20 10
Subtracting two pointers: If two pointers are associated with the same array, then subtraction of
two pointers is allowed. But,if the two pointers are associated with different arrays, even though
subtraction of two pointers is allowed. The result is meaningless.
Example: int a[5] = {10,20,30,40,50};
int *p1;
int *p2;
float *f;
p1= a;
p2= &a[4];
The various valid and invalid statements are
p2– p1; it is valid
p1– p2; it is valid
f – p1 it is invalid since type of both operands is not same.

10 20 30 40 50

100 102 104 106 108


But, p2-p1 is not 0108 - 0100. Actually, it is (0108-0100)/sizeof(int) i.e;(0108 - 0100)/2 = 4.
Comparing two pointers: If two pointers are associated with the same array. Then comparison of
two pointers is allowed using operators.
Example: int a[5] = {10,20,30,40,50};
int *p1, *p2;
float *f;
p1= a;
p2 = &a[4];

CSE DEPT. Page 11


Data Structures

p2!= p1;--------------valid
p1== p2;-------------valid
p1<= p2;--------------valid
p1>= p2;--------------valid
f!= p1;----------------invalid
Example: #include<stdio.h>
main()
{
int a=20,b=10;
int *p, *q;
p=&a;
q=&b;
printf(“addition of two pointers is:%d”,(*p)+(*q));
printf(“subtraction of two pointers is:%d”,(*p)-(*q));
printf(“multiplication of two pointers is:%d”,(*p)*(*q));
printf(“division of two pointers is:%d”,(*p)/(*q));
printf(“mod of two pointers is:%d”,(*p)%(*q));
getch();
}
Pointers and functions:
Pointers as function arguments: Here, we can pass the addresses to a function, and then the
parameters receiving the address should be pointers. The process of calling a function using pointers
to pass the address of variables is known as call by reference (or) call by address (or) pass by
pointers. The function which is called by reference can change the value of the variable used in the
call.
Example: #include<stdio.h>
main()
{
int x;
x=20;
change(&x);
printf(“%d”,x);
}
change(int *p)
{
*p=*p+10;
}
Example: #include<stdio.h>
void exchange(int *m, int *n);
void main()
{
int a=10,b=20;
printf(“values before exchange a=%d,b=%d”,a,b);
exchange(&a,&b);
printf (“values after exchange a=%d,b=%d”,a,b);
}
void exchange (int *m, int *n)
{
int temp;
temp=*m;
CSE DEPT. Page 12
Data Structures
*m=*n;

CSE DEPT. Page 13


Data Structures

*n=temp;
}
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
name of an array itself indicates the stating address of an array or address of first element of an
array. That means array name is the pointer to starting address or first elements of the array. If x is
an array then address of first element can be expressed as &x[0] .The compiler defines array name
as a constant pointer to the first element.
Example: int x[5]={1,2,3,4,5};
In the above declaration , assume the base address of x is 1000 and assuming that each integer requires
two bytes, the five elements will be stored as follows
Elements--------> x[0] x[1] x[2] x[3] x[4]

Value--------------------------------------------------> 1 2 3 4 5
Address---------> 1000 1002 1004 1006
1008

Base address
The name x is defined as a constant pointer pointing to the first element, x[0] and therefore the value
of x is 1000,the location where x[0] is stored. That is
x=x[0]=1000
if we declare p as an integer pointer, then we can make the pointer p to point to the array x by the
following assignment:
p=x;
The above statement is equivalent to p=&x[0].
Now, we can access every value of x using p++ to move from one element to another. The relationship
between p and x is:
p=&x[0](=1000)
p+1=&x[1](=1002)
p+2=&x[2](=1004)
p+3=&x[3](=1006)
p+4=&x[4](=1008)
Note that the address of an element is calculated using its index and the scale factor of its data type.
Example: address of x[3]=base address+(3*scale factor of int)
=1000+(3*2)
=1006
When handling arrays, instead of using array indexing, we can use pointers to access array elements.
Note that *(p+3) gives the value of x[3].that is 1006.

CSE DEPT. Page 14


Data Structures

The pointer access method is faster than array indexing.


Example: #include<stdio.h>
#include< conio.h>
main( )
{
int *p,i,sum;
int x[5]={5,9,6,3,7};
i=0;
p=x;
printf(“Element value address”);
while(i<5)
{
printf(“x[%d] %d %u”,i,*p,p);
sum=sum+ *p;
i++;
p++;
}
printf(“\n sum=%d\n”sum);
printf(“\n &x[0]=%u\n”&x[0]);
printf(“\np=%u\n”p);
}
Output: element value address
X[0] 5 166
X[1] 9 168
X[2] 6 170
X[3] 3 172
X[4] 7 174
Sum=55
&x[0]=166
P=176
Example: #include <stdio.h>
main( )
{
int *p;
int val[7] = { 11, 22, 33, 44, 55, 66, 77 } ;
p = &val[0];
for ( int i = 0 ; i <= 6 ; i++ )
{
printf("val[%d]: value is %d and address is %u", i, *(p+i), (p+i));
}
}

Example: #include <stdio.h>


main( )
{
int a[5]={10,20,30,40,50};
int i=3; printf(“%d%d%d
%d”,*(&a[i]),a[i],*(a+i),*(i+a));
}
Output: 40 40 40 40
Example: #include <stdio.h>

CSE DEPT. Page 15


Data Structures

main( )
{
int a[10],n,i,big;
printf(“enter no of elements”);
scanf(“%d”,&n);
printf(“enter array elements”);
scanf(“%d”,(a+i));
big=*(a+0);
for(i=0;i<n;i++)
{
if(*(a+i)>big)
{
big=*(a+i);
}
}
printf(“largest no is%d:”,big);
}
Example: #include <stdio.h>
main( )
{
int a[10],n,i,sum;
int *p=a;
printf(“enter no of elements”);
scanf(“%d”,&n);
printf(“enter array elements”);
for(i=0;i<n;i++)
{
scanf(“%d”,(p+i));
p++;
}
for(i=0;i<n;i++)
{
sum=sum+*p;
p++;
}
printf(“sum of n no is is%d:”,sum);
}
Pointers to two dimensional arrays: pointers can be used to manipulate two dimensional arrays as
well. we know that in a one dimensional array x, the expression is
*(x+i) or *(p+i)
The above declaration represents the element x[i], similarly an element in 2D array can be represented
by the pointer expression is
*(*(a+i)+j) or *(*(p+i)+j)
Example: COLUMNS
0 1 2 3 4 5
0 p

CSE DEPT. Page 16


Data Structures

R 1 p+1

0 2

W 3

S 4 4,0 4,3 p+4

6 p+6

*(p+4)
*(p+4)+3
Here, p ---> pointer to the first row
p+i ---> pointer to the ith row
*(p+i)---> pointer to 1st element in the ith row
*(p+i)+j)- - ->pointer to jth element in the ith row
*(*(p+i)+j)- ->pointer to the ith row jth cell
The above example, base address of the array a is &a[0][0] and starting at this address. The compiler
allocates contiguous space for all the elements row wise. That is the first element of the second row
is placed immediately after the last element of the first row and so on.
Example: int a[3][4]={{15,27,11,35}
{22,19,31,17}
{31,23,14,36}
};
The elements a will be stored as
<====== row0=====><=====row1=======><====row2=======>
15 27 11 35 22 19 31 17 31 23 14 36

Address=&a[0][0] 100 102 104 106 108 110 112 114 116 118 120 122
P p+1 p+2
By using &p[i][j] or *(p+i)+j we can obtain address of ith row jth column.
By using p[i][j] or *(*(p+i)+j) we can obtain value ith row and jth column.
Example:
#include<stdio.h>
void main ( )
{
int i,m,n, a[10][20], b[10][20];
printf (“Enter the size of the matrix m & n: \n”);

CSE DEPT. Page 17


Data Structures

scanf(“%d%d”, &m, &n);


printf (“enter the matrix a \n”);
read_matrix (a, m, n);
printf (“enter the matrix b\n”);
read_matrix (b, m,n);
printf(“ the matrix is \n”);
write-matrix (c ,m, n);
}
void read_matrix(int *a[10], int m, int n)
{
int i, j;
for (i = 0; i<m; i++)
{
for (j=0; j<n; j++)
{
scanf (“%d”, (*(a+i) + j) );
}
}
}
void write_ matrix(int *b[10], int m, int n)
{
int i, j;
for(i = 0; i<m; i++)
{
for (j=0; j<n; j++)
{
printf (“%d”, *(*(a+i) + j) );
}
printf (“\n”);
}
}
Example: Program to add two matrices using pointers.
#include<stdio.h>
void read_matrix(int *a[10], int m, int n)
{
int i, j;
for (i = 0; i<m; i++)
{
for (j=0; j<n; j++)
{
scanf (“%d”, (*(a+i) + j) );
}
}
}
void write_ matrix(int *b[10], int m, int n)
{
int i, j;
for(i = 0; i<m; i++)
{
for (j=0; j<n; j++)
{
printf (“%d”, *(*(a+i) + j) );
CSE DEPT. Page 18
Data Structures

}
printf (“\n”);
}
}
void add_ matrix ( int * a[10], int *b[10], int *c[10], int m, int n)
{
int i, j;
for (i = 0; i<m; i++)
{
for (j=0; j<n; j++)
{
*( *( c+i ) + j) = *(*(a+i) + j) + * ( *(b+i) + j);
}
}
}
void main ( )
{
int i,m,n, a[10][20], b[10][20], c[10][20];
printf (“Enter the size of the matrix m & n: \n”);
scanf(“%d%d”, &m, &n);
printf (“enter the matrix a \n”);
read_matrix (a, m, n);
printf (“enter the matrix b\n”);
read_matrix (b, m,n);
add_matrix(c,m,n);
printf(“ the resultant matrix is \n”);
write-matrix (c ,m, n);

}
Pointers and strings: we have seen earlier that strings are treated like character arrays and therefore,
they are declared and initialized as follows.
Example: char array[ 11] = “Love India”;
The compiler will automatically inserts the null character (‘\0’) at the end of the string.
C language supports to create strings using pointer variables of type char
Example: char *p= “Love India”;
Here the pointer p now points to the first character of the string love india as
L O V E I N D I A \0

We can also use the runtime assignment for giving the values to a string pointer.
Example: char *p;
P=”good”;
We can print the content of string p using printf() and puts().
Example: printf(“%s”,p);
puts(p);

CSE DEPT. Page 19


Data Structures

Remember p is a pointer to the string, it is also name of the string. Therefore, we do not need to use
indirection operator * here.
We can also use pointers to access the individual characters in a string.
Example: #include<stdio.h>
#include<conio.h>
main()
{
int i;
char *p= “ Love India”;
clrscr();
while (*p! = “\0‟)
{
printf (“ %c “, *p);
p++;
}
}
Output: Love India
Array of pointers: one important advantage of pointers is in handling of a table of strings using
array of pointers.
Example: char name[3][25];
The above syntax tells that the name is a table containing three names, each with maximum length of
25 characters (including null character).The total storage requirements for the name table are 75
bytes. We know that the individual strings will be of equal lengths. Therefore, instead of making
each row a fixed number of characters, we can make it a pointer to a string of varying length.
Example: char *name[3]={ “new Zealand”,
“Australia”
“india”
};
In the above example declares name to be an array of three pointers to characters, each pointer
pointing to a particular name as:
Name[0]------->new Zealand
Name[1]------->india
Name[1]-------->Australia
This declaration allocates 28 bytes, sufficient to hold all the characters.
N E W Z E A L A N D \0

A U S T R A L I A \0

I N D I A \0

The following statement would print out all the three names

CSE DEPT. Page 20


Data Structures

for(i=0;i<=2;i++)
{
printf(“%s\n”,name[i]);
}
To access the jth character in the ith name, we may write it as
*(name[i]+j)
The character arrays with the rows of varying length are called ragged arrays
Pointers to pointers (or) chain of pointers: A pointer to point to another pointer is called pointer to
a pointer (or) chain of pointers.

Here the pointer variable p1 contains the address of the pointer variable p2,which points to the
location that contains the desired value. this is known as multiple indirections.
A variable that is a pointer to a pointer must be declared using additional indirection operator symbols
in front of the name.
Syntax: int **p1;
In the above syntax tells the compiler that p1 is a pointer to a pointer of int type. Remember, the
pointer p1 is not a pointer to an integer, but rather a pointer to an integer pointer.
Example: #include<stdio.h>
main()
{
int x,*p2,**p1;
x=100;
p2=&x;
p1=&p2;
printf(“%d”,**p1);
}
Example: #include <stdio.h>
void main()

int k = 5;
int *p = &k;
int **m = &p; printf("%d%d%d\
n", k, *p, **m);
}
Output: 555
void pointer (or) generic pointer: a void pointer is a special type of pointer, that can be pointed to
any data type. Hence, void pointer is also called as universal (or) generic pointer .A void pointer is
declared like a normal pointer, using the void keyword as the pointer’s type. void pointers are useful
for pointing different data types.

CSE DEPT. Page 21


Data Structures

Syntax: void *identifier;


Example: void *p;
Now the pointer variable p can contain address of data variable of any type such as int, float,char and
double etc. The only limitation is that the pointed data cannot be referenced directly using indirection
operator. This is because; its length is always undetermined.
Example: #include<stdio.h>
main()
{
int i;
char ch;
void *p;
i=6;
ch=’a’;
p=&i;
printf(“the value of I is%d”,*(int*)p);
p=&ch;
printf(“the value of ch is %c”,*(ch*)p);
}
Pointers to functions: a function, like a variable, has a type and an address location in the
memory.so it is possible to declare a pointer to a function, which can be used as an argument in
another function. A pointer to a function is declared as follows
Syntax: datatype (*fptr)();
This tells the compiler that fptr is a pointer to a function, which returns data type value.
We can make a function pointer to point to a specific function by simply assigning the name of the
function to the pointer.
Example: double mul(int,int);
double(*p)();
p=mul;
Here declare p is pointer to a function and then make p to point the function mul. To call the
function mul,we may now use the pointer p with list of parameters. That is
(*p)(x,y);/* function call */
The above statement is equivalent to
mul(x,y);
Example: # include<stdio.h> main( )
{
int show ( )
int (*p) ( );
clrscr();
p = show;
p( ); /* equals to (*p)(); */
printf (“%u”, show);
getch();
}
CSE DEPT. Page 22
Data Structures

show ( )
{
printf( “the address of function show is : “);
}
Output: the address of function show is 759
In this program the variable p is pointer to function. Address of function show ( ) is assigned
to pointer p. Using function pointer, the function show ( ) in invoked.
Example: #include<stdio.h>
main()
{
int(*fptr)(int,int); /*Function pointer */
fptr = func; /* Assign address to function pointer */
func(2,3);
fptr(2,3); /* it is equals to (*fptr)(2,3); */
}

int func (int a, int b)


{
printf("\n a = %d\n",a);
printf("\n b = %d\n",b);
return 0;
}
Output: a=2
b=
3
a=2
b=
3
Functions returning pointers: we have seen so far that a function can return single value by using
return statement (or) return multiple values through pointer parameters. since pointers are a data type
in c, we can return a pointer to the calling function.
Syntax: datatype *fptr();
Where fptr is a function returning a pointer to data type.
Example: #include<stdio.h>
int *larger(int *,int *);
main()
{
int a=10;
int b=20;
int *p;
p=larger(&a,&b);
printf(“%d”,*p);
}
int *larger(int *x,int *y)
{
if(*x>*y)
return (x); /* return address of a */
else
return (y); /* return address of b */
}
CSE DEPT. Page 23
Data Structures
Here, the function larger receives the addresses of the variables a and b, decides which one is larger

CSE DEPT. Page 24


Data Structures

using the pointers x and y and then returns the address of its location. The returned
value is then assigned to the pointer variable p in the calling function. In this case, the
address of b is returned and assigned to p and therefore the output will be the value of
b,that is 20.
Advantages:
More than one value can be returned using pointer concept.
Very compact code can be written using pointers.
Data accessing is much faster when compared to arrays.
Using pointers, we can access byte (or) word locations and the CPU registers
directly. The pointers in „C‟ are mainly useful in processing of non – primitive
data structures such as arrays, linked lists etc.,
Disadvantages:
Un-initialized pointers or pointers containing invalid address can cause system
crash.
It is very easy to use pointers incorrectly, causing bugs that are very difficult to
identify and correct.
They are confusing and difficult to understand in the beginning and if they are
misused. The result is not predictable.

CSE DEPT. Page 25

You might also like