Monday, March 14, 2016

C Strings - Internal Working and Functions with example

Unlike other languages like C++, Java, etc. C does not provide any dedicated data type, rather it uses a character array to store strings. Since, in programming practices, we encounter frequently to handle strings. It is good to know how to do this in C.
Strings in C
As mentioned earlier, in C handles strings in a different manner, uses a character array to store. Now, after reading the Chapter: Arrays in C Language, you might have confused that there was something called character array and C uses also a character array to store strings, then how both gets differ with each other ?

Actually, there is a slight difference between simple character array and strings. A string always ends with ‘\0’ or NULL character which is not mandatory for a simple character array. 

Initializing Strings in C

Strings in C can be initialized in various ways and for every method there are some important points you should remember.
char arr[] = {‘A’,’4’,’A’,’C’,’A’,’D’,’E’,’M’,’I’,’C’,’S’,’\0’};
This is the simplest way to initialize the strings. It is same like the character array initialization, but only difference is that there is a ‘\0’ character at the end. Here, the size of the array is not mentioned, so it will automatically allocate memory for 8 characters (8 bytes since a character takes 1 byte) including the ‘\0’ character.
Method 2:
char arr[] = “A4ACADEMICS”;
This is another way to initialize the array. Here, the compiler automatically inserts a ‘\0’ at the end.
Method 3:
char arr[10] = {‘A’,’4’,’A’,’C’,’A’,’D’,’E’,’M’,’I’,’C’,’S’,’\0’};
In this method, arr holds 10 byte of memory as per declaration. From the 0th index to 6th index it will hold the word “STRING” and 7th location holds ‘\0’ character and 8th and 9th location holds garbage values.
Method 4:
char *arr = “A4ACADEMICS”;
This is another interesting way to initialize strings. Specifically, this is called string literals. The most interesting thing in this method is that after this declaration you can’t change the value of the string. This will be constant string literals throughout its scope.

No comments: