A note on strings and char*

Since C holds strings in arrays of char terminated with the null character, '\0', parameters requiring strings are passed as char *. This means that the contents of a string can be changed in a function to which it is passed.

Many strings in programs are actually literal sequences of characters enclosed in double quotes. These do not occupy space in the runtime memory of the program, at least not modifiable space. Thus it is important not to pass such constant strings to functions where they will be overwritten. To prevent mistakes of this sort, C has the specifier const, which is used to define parameters as const char *. A compiler should check that no assignment is made to such a string. The const applies to the contents, not the pointer itself, which can be modified by assignment or other operations to point elsewhere. In practice it is impossible to check all ways that such a string could be the target of an assignment.

Most string handling library functions use const char * for this reason.


Next - Dynamic memory allocation in C.

Back to Contents page.