Monday, 27 May 2013

Strings

The way a group of integers can be stored in an integer array, similarly a group of characters can be stored in a character array. These arrays of characters many a times called as Strings. A string constant is a one-dimensional array of characters terminated by a NULL or '\0'. Each character in the array occupies one byte of memory and the last character or the always the terminating character of string in C lang is NULL or '\0'
NOTE: \0 and 0 are not the same as the ASCII value of \0 is 0 and ASCII value of 0 is 48.

Null character can be defined in three types:
  1. '\0'
  2. NULL
  3. #define NULL 0
The terminating null is important, because its only the way that the function, working with string, can know where the string ends. In fact, a string not terminated by a null character is merely a sequence or collection of characters but not a string.

Lets see a program on string.

char str[10]="sat";
printf("%s",str);

Here str[10] is assigned with 10 bytes of memory allocation in which three has been assigned with "sat". Then what happens to rest of the locations? Yet those are wasted but string automatically assign a null character to the end of the characters i.e. after 't' a null character is set in the memory location. I have marked a green colored '%s" in the printf command line. It shows the format of the  printing, and here it is format string so it will print the strings only till the terminating end (NULL).

Suppose you assigned something in a variable str and now you want changes in it how would you do?
It will be like

str[0]='t';    |     *(str+0)='t';
str[1]='a';            *(str+1)='a';
.       |           .
.       |           .
.       |           .
.       |           .
str[n]='B';        |        *(str+n)='B';

So array would cover all the locations of the mentioned string and hence we can probably change the content in the location of the string.














No comments:

Post a Comment