Character Array
We know array is a group of data elements of same data type. Array can be of any basic data type i.e. int, char, double or float. A character array is nothing but an array declared as character data type.
Eg: char name[5];
String
A string in C Language is also character array but has a special termination character null i.e. � as its last element.
Difference between String and Character Array
The basic difference between a string and character array is the array is a group of characters but string is a group of character with additional terminal character. C Language can only accommodate the null character automatically only when a character array has additional space.
//Example code showing basic difference between a character array and string
#include
void main()
{
char city1[3]={‘R’,’J’,’Y’}; //character array
char city2[3]=”RJY”; //character array
char city3[]=”RJY”; //string
char city4[4]={‘R’,’J’,’Y’,’\0′}; //string
printf(“size of city1 %d”,sizeof(city1));
printf(“\nsize of city2 %d”,sizeof(city2));
printf(“\nsize of city3 %d”,sizeof(city3));
printf(“\nsize of city4 %d”,sizeof(city4));
}
Advantages of Strings over character array
Basically we use character arrays to store group of characters indicates meaningful words or phrases. After then, we want to perform some operations on the words or phrases like getting the size of word, comparing two words, appending one word to another etc. These operations are complex when you store them as character array. As a solution to this problem, C Language is providing a special header file called ‘string.h’ with many built-in functions to work with strings. These functions may not work correctly with character arrays.
//Example code showing advantage of strings over character arrays
#include
#include
void main()
{
char city1[3]={‘R’,’J’,’Y’}; //character array
char city2[3]=”RJY”; //character array
char city3[]=”RJY”; //string
char city4[4]={‘R’,’J’,’Y’,’\0′}; //string
printf(“\n\n”);
printf(“size of city1 %d”,strlen(city1));
printf(“\nsize of city2 %d”,strlen(city2));
printf(“\nsize of city3 %d”,strlen(city3));
printf(“\nsize of city4 %d”,strlen(city4));
printf(“\n\n”);
strcat(city3,city4);
printf(“\n%s”,city3);
strcat(city1,city2);
printf(“\n%s”,city1);
}