Initialization of Strings in C Language

The string can be initialized as follows:

char name[ 8] = {‘P’, ‘R’, ‘O’, ‘G’, ‘R’, ‘A’, ‘M’, ‘\0’};

 

Each character of string occupies 1 byte of memory (on 16 bit computing). The size of the character is machine dependent and varies from 16 bit computers to 64 bit computers. The characters of strings are stored in the contiguous (adjacent) memory locations.

1 byte 1 byte 1 byte 1 byte 1 byte 1 byte 1 byte 1 byte
P R O G R A M \0
1001 1002 1003 1004 1005 1006 1007 1008

 

The C compiler inserts the NULL (\0) character automatically at the end of the string. So initialization of the NULL character is not essential.

You can set the initial value of a character array when you declare it by specifying a string literal. If the array is too small for the literal, the literal will be truncated.

If the literal (including its null terminator) is smaller than the array, then the final characters in the array will be undefined.

If you don’t specify the size of the array, but do specify a literal, then C will set the array to the size of the literal, including the null terminator.

char str[4] = {‘u’, ‘n’, ‘i’, ‘x’};
char str[5] = {‘u’, ‘n’, ‘i’, ‘x’, ‘\0’};
char str[3];
char str[ ] = “UNIX”;
char str[4] = “unix”;
char str[9] = “unix”;

 

All of the above declarations are legal. But which ones don’t work?

The first one is a valid declaration but will cause major problems because it is not null-terminated.

The second example shows a correct null-terminated string. The special escape character \0 denotes string termination.

The fifth example suffers the size problem, the character array ‘str’ is of size 4 bytes, but it requires an additional space to store ‘\0’.

The fourth example, however, does not. This is because the compiler will determine the length of the string and automatically initialize the last character to a null-terminator.

The strings not terminated by a ‘\0’ are merely a collection of characters and are called as character arrays.

 

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: