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.
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:
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.|
Pointer and Array of Strings
Array of strings is actually a two dimensional array of char data type.
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
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.|
int i;printf(“\nNames are:=”);
Best Books of C