Pointer with Strings in C

Preview
You must first complete Pointer with Array in C before viewing this Lesson

Pointer with Strings in C

In C language, a string is represented as a character array. When we declare a string, we need to specify size of string just as we do  in arrays.

Example
char sname[14];

In this example sname is a string variable which can contain maximum 14 characters including null character. So there is a limitation of size and we can’t store more than 14 characters in this string variable.

Suppose we store “India” in this variable. The value “India” contains 6 characters including null character. So there is a wastage of 8 spaces as size of string variable sname is 14.

Both these limitations of character type array can be rectified with the help of pointer.

We can declare a string variable using pointer as:

char *sname;

Now, this string variable sname can contain any number of characters depending upon the programmer’s requirement and there is no wastage of space as size will be automatically taken by the compiler depending upon the value stored in this string variable.



Program to use string with pointer.
#include<stdio.h>
int main()
{
char *sname;
sname=”Lovejot Bhardwaj”;
printf(“\nname=%s”,sname);
return(0);
}
Output
name=Lovejot Bhardwaj




Pointer and Array of Strings

Array of strings is actually a two dimensional array of char data type.
Example
char sname[5][14];
In this case sname is an array of strings which can contain 5 values each of which can contain maximum 14 characters. Now there is again a limitation i.e. each element of array of strings can’t contain more than 14 characters and if lesser number of characters are stored, there is again wastage of memory.
The alternative approach to the above declaration of array of strings is
char *sname[5];
Now, the array of string sname can contain five strings each of which can have any size depending upon the requirement.


Program to demonstrate the array of strings using pointer.
#include<stdio.h>
int main()
{
char *name[4]={“Lovejot”,”Amit”,”Anoop”,”Arun”};
int i;
printf(“\nNames are:=”);
for(i=0;i<4;i++)
printf(“\n%s”,name[i]);return(0);
}
Output
Names are:=
Lovejot
Amit
Anoop
Arun

Best Books of C





Lesson tags: array of strings using pointer, handling strings using pointer, program to use string using pointer, string type pointer variable
Back to: C Programming Language