Page 72 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 72
Unit 5: Pointers
How can we do this?. Let us discuss with the example given below. Notes
Example:
Store lines end-to-end in one big char array (Figure 5.4). n will delimit lines.
Store pointers in a different array where each pointer points to 1st char of each new line.
Compare two lines using strcmp() standard library function.
If 2 lines are out of order — swap pointer in pointer array (not text).
Figure 5.4: Arrays of Pointers (String Sorting Example)
This eliminates:
complicated storage management.
high overheads of moving lines.
Example:
Lets take a working example :
#include<stdio.h>
int main(void)
{
char *p1 = “Himanshu”;
char *p2 = “Arora”;
char *p3 = “India”;
char *arr[3];
arr[0] = p1;
arr[1] = p2;
arr[2] = p3;
printf(“\n p1 = [%s] \n”,p1);
printf(“\n p2 = [%s] \n”,p2);
printf(“\n p3 = [%s] \n”,p3);
LOVELY PROFESSIONAL UNIVERSITY 65