An array of characters is called a string.
Declaration
The syntax for declaring an array is as follows −
char stringname [size];
For example − char string[50]; string of length 50 characters
Initialization
- Using single character constant −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
- Using string constants −
char string[10] = "Hello":;
Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’.
Now, let us understand what are the arrays of pointers in C programming language.
Arrays of pointers: (to strings)
- It is an array whose elements are ptrs to the base add of the string.
- It is declared and initialized as follows −
char *a[ ] = {"one", "two", "three"};
Here, a[0] is a pointer to the base add of string "one".
a[1] is a pointer to the base add of string "two".
a[2] is a pointer to the base add of string "three".
Example
Following is a C program demonstrating the concepts of strings −
#include<stdio.h> #include<string.h> void main(){ //Declaring string and pointers// char *s="Meghana"; //Printing required O/p// printf("%s\n",s);//Meghana// printf("%c\n",s);//If you take %c, we should have * for string. Else you will see no output//// printf("%c\n",*s);//M because it's the character in the base address// printf("%c\n",*(s+4));//Fifth letter a because it's the character in the (base address+4)th position// printf("%c\n",*s+5);//R because it will consider character in the base address + 5 in alphabetical order// }
Output
When the above program is executed, it produces the following result −
Meghana M a R
Example 2
Consider another example.
Given below is a C program demonstrating the concepts of printing characters using the post increment and pre increment operators −
#include<stdio.h> #include<string.h> void main(){ //Declaring string and pointers// char *s="Meghana"; //Printing required O/p// printf("%s\n",s);//Meghana// printf("%c\n",++s+3);//s becomes 2nd position - 'e'. O/p is Garbage value// printf("%c\n",s+++3);//s becomes 3rd position - 'g'. O/p is Garbage value// printf("%c\n",*++s+3);//s=3 becomes incremented by 1 = 'h'.s becomes 4th position.h+3 - k is the O/p// printf("%c\n",*s+++3);//s=4 - h is the value. h=3 = k will be the O/p. S is incremented by 1 now. s=5th position// }
Output
When the above program is executed, it produces the following result −
Meghana d d k k