In the above example , each string is of a fixed size of 20 characters . However, the size of each name may be different. In this case, we can use dynamic memory allocation to allocate memory separately for each string.
If we use dynamic memory allocation for one string, we require one pointer.
char *ptr; //one pointer
ptr=(char *) malloc(20*sizeof(char)); //one string of 20 chars Since We have many string, we need many pointers. Hence, we must use an array of pointers, each pointer pointing to a string.
The following diagram shows 10 pointers, each pointer pointing to one string.
In following example, we shall see how a list of ‘n’names can be stored as an array of pointers. Currently, we will allocate memory for ‘n’names, and allocate 10 characters for each name.
Array of Character Pointers Example
#include< stdio.h>
#include<string.h>
main()
{ char *ptr[20];
int i,n;
printf(“\nHow many names?”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{ ptr[i]=(char *) malloc(10*sizeof(char));
printf(“\nEnetr name%d”,i);
gets(ptr[i]);
}
printf(“\nThe names in the list are:”);
for(i=0;i<n;i++)
{
puts(ptr[i]);
}
}
Comments
Post a Comment
Please give us feedback through comments