Initializing Strings:


In the previous chapter, we discussed that how numeric arrays can be initialized. Similarly, strings which are basically character arrays can also be initialized. The following example shows different ways of initializing strings:
            char name [6] = “HELLO”;
or        char name [6] = {‘H’, ‘E’, ‘L’, ‘L’, ‘L’, ‘O’, ‘\0’};
or        char name [ ] = “HELLO”.

In the first method of initialization, the compiler allocates space for 6 characters for array name. The first six characters are filled with ‘H’, ‘E’, ‘L’, ‘L’, ‘O’ characters and with character ‘\0’ (null character) automatically. In memory, it appears as shown in:


The second method of initialization also copies the individual characters into the array name in the same way as in the previous initialization except that the user has to explicitly specify the null character (‘\0’) to make the end of character array so that it can be used as a string. However, if the user specifies the array size less than number of characters initializing to it then it may give error. For example:
                                    char name [5] = {‘H’, ‘E’, ‘L’, ‘L’, ‘L’, ‘O’, ‘\0’};

In the above initialization, as there is no space in the character array for storing null character (‘\0’) which makes the array unusable as a string. It causes unpredictable result during the execution of the program. This problem can be overcome by specifying the size large enough to hold all the characters of the string including null character (‘\0’). As it is always difficult to count for the exact size, so a rough approximation should follow.
For example: The statement,
                                    char name [10] = “HELLO”;

In the above initialization, the compiler allocates space for 10 characters, where first 6 characters are fill with ‘H’, ‘E’, ‘L’, ‘L’, ‘O’ and ends with ‘\0’. The remaining 3 spaces of the character array are filled with null character (‘\0’) automatically. This method of initialization results in wastage of memory.


A better of method of initializing is to omit the size of the character array at time of its initialization. In such a case, compiler automatically computes the size.
                                    char name [ ] = “HELLO”;
As a result of this initialization, the compiler sets aside memory for 6 characters for array name, large enough to store all characters including a null character. This method of initialization is useful in those situations in which string is very long, as calculating the length manually may be difficult.



Previous                                                                                    Next


Powered by Blogger.