C Tutorial C Strings

Data types in C
Arrays in C
Pointers in C
Pointer Dereferencing
The & Operator
Uninitialized Pointers
Using Pointers
C Strings

String Code Example
Large Strings
Char type pointers




C has minimal support of character strings. For the most part, strings operate as ordinary

arrays of characters. Their maintenance is up to the programmer using the standard

facilities available for arrays and pointers. C does include a standard library of functions

which perform common string operations, but the programmer is responsible for the

managing the string memory and calling the right functions. Unfortunately computations

involving strings are very common, so becoming a good C programmer often requires

becoming adept at writing code which manages strings which means managing pointers

and arrays.

A C string is just an array of char with the one additional convention that a "null" character ('\0') is stored after the last real character in the array to mark the end of the string. The compiler represents string constants in the source code such as "binky" as

arrays which follow this convention. The string library functions (see the appendix for a partial list) operate on strings stored in this way. The most useful library function is strcpy(char dest[], const char source[]); which copies the bytes of one string over to another. The order of the arguments to strcpy() mimics the arguments

in of '=' -- the right is assigned to the left. Another useful string function is strlen(const char string[]); which returns the number of characters in C string not counting the trailing '\0'.


Note that the regular assignment operator (=) does not do string copying which is why strcpy() is necessary. See Section 6, Advanced Pointers and Arrays, for more detail on how arrays and pointers work.


The following code allocates a 10 char array and uses strcpy() to copy the bytes of the string constant "binky" into that local array.



char localString[10];


strcpy(localString, "binky");




The memory drawing shows the local variable localString with the string "binky" copied into it. The letters take up the first 5 characters and the '\0' char marks the end of the string after the 'y'. The x's represent characters which have not been set to any particular value.


If the code instead tried to store the string "I enjoy languages which have good string support" into localString, the code would just crash at run time since the 10 character

array can contain at most a 9 character string. The large string will be written passed the right hand side of localString, overwriting whatever was stored there.

Want To Know more with

Video ???