Passing String to Functions
As other variables, a String can also be passed to a function. It is similar to that of passing arrays to a function because strings are also called as character arrays.
Example:
#include<stdio,h> #include<conio.h> #include<string.h> void main() { char str[20]; clrscr(); printf("\n Enter a String"); gets(str); fun(str); getch(); } fun (char s[20]); { printf("\n String passed is"); puts(s); }
Output
Enter a String Hello
String passed is Hello
Array of Strings
- A two dimensional array of characters is known as an array of String.
- The row subscript i.e. the first subscript decides as to how many strings can be stored in the array and the col Subscript i.e. the second subscript tells the size of each strings.
- For Example, an array called dir of 10 strings of 20 characters each can be declared as shown below: –
char dir[10][20];
Free E-Books and Notes
- Once the declaration is obeyed, we get a group of 10 memory locations of string type.
- In this kind of arrangement, a string can be accessed by the row subscript.
- For instance, the 4th string in array dir can be read from the keyboard by the following statement: –
Example: Demonstration of arrays of strings
#include<stdio,h> #include<conio.h> #include<string.h> void main() { char str[20]; clrscr(); printf("\n Enter names of 10 persons"); for(i=0; i<10; i++) { fflush(stdin); gets(name[i]); } printf("\n Enterd names are... \n"); for(i=0; i<10; i++) puts(name[i]); }
- But this method of representing list of strings has one serious problem of memory wastage.
- As in the example, we assumed that the name could be upto 20 characters long, so we have declared the strings of length 20.
- But some names may be of few characters long while others may be of half of the declared length.
- So on the average, half of the allocated space goes wasted.
- This problem of memory wastage can be solved using array of pointers to strings in the chapter of pointers.