String Representation

In C, a string is stored as an array of type char. All strings should be terminated with the character '\0'. Many routines will expect this symbol and use it to know where the string ends. When a string is declared using quotation marks, the \0 character is automatically added to the end of the string. Many functions like strcpy also add the character, but other functions do not.

Strings can be problematic in C. It is very important that you do not put more characters in a string then you have allocated space for. For instance, if you have allocated char sampleString[5];, you cannot store the word Kiriari in sampleString. The extra letters will be written into memory, probably corrupting other data the program relies on. Overflowing strings is one of the main sources of hard to find bugs in C programs.

As in the above example, strings can be allocated simply by declaring the an array of char. Note that when specifying the length of a string, you must include one space for the '\0' termination character. For example:

char sam[10];
allows space for a nine letter string plus the termination character.

It is very common to use pointer to strings. These can simply be declared as:

char * sampleStringPointer;

next


 home                      table of contents                      about