Pages

Saturday, November 14, 2009

Character Arrays (Strings)

Introduction

Till now all the arrays we have created are either of type int or float but we can also create arrays of character type. Such arrays are more popularly called “Strings”. Strings can be defined as a collection of characters terminated by null character (‘\0’) - Zero. If the collection is not terminated by ‘\0’ (zero) then it will not be called as string but just a collection of characters. They are used to store multi character values like name, address etc. They can also be used for storing integers or symbols since char allows any type of value. Strings in C are used with the modifier %s during input and output operations.

The null character – ‘\0’
The ‘\0’ plays a vital role in a string. It marks the end of a string so that when the string is printed or processed the compiler is aware that where the end of string is. Let’s understand this with an example
Example 1: Basic string input output program

void main()
{
char name[10]; //string declared with a size of 10
printf(“\nWhat’s your name ? “);
scanf(“%s”,&name); // %s denotes string.
printf(“Hello %s”,name);
}
Description
The above code declares a string (or char array) named “name” which can accept 10 characters. When the user enters his/her name the same is stored in the string starting from index 0. The C compiler automatically appends ‘\0’ after the last character to mark the end of the string. When the string is printed the compiler prints the string from the first character housed at index 0 till it reaches the ‘\0’ mark.
Output
What’s your name? Steven
Hello Steven

Why ‘\0’ is needed?
The moment we declare a string it is filled with garbage values. For example the declaration “char str[20]” will not only create a string with a capacity of 20 characters but will also fill it with 20 garbage characters. Now if the user enters a string having 12 characters the garbage values in the first 12 elements will be replaced by the characters entered by the user but the remaining 8 elements will still be garbage values. To prevent these garbage values from printing C adds the ‘\0’ after the 12th character. If this character wasn’t there then garbage values will also be printed causing unwanted character on the screen.

Example 2: Understanding the use of ‘\0’
void main()
{
char str[25];
printf(“Type a sentence (max. 25 characters) : “);
scanf(“%s”,&str);
printf(“\nyou entered %s”,str);
for(int i=0;i<25;i++)
{
printf(“\n%c”,str[i]);
}
}

0 comments:

Post a Comment