Node:Initializing strings, Next:String arrays, Previous:Conventions and declarations, Up:Strings
Initializing string variables (or character arrays) with string values
is in many ways even easier than initializing other kinds of arrays.
There are three main ways of assigning string constants to string variables.
(A string constant is a string value that was typed into the source
code, as opposed to one that is generated by the program or entered by the user.)
#include <stdio.h> #include <string.h> int main() { /* Example 1 */ char string1[] = "A string declared as an array.\n"; /* Example 2 */ char *string2 = "A string declared as a pointer.\n"; /* Example 3 */ char string3[30]; strcpy(string3, "A string constant copied in.\n"); printf (string1); printf (string2); printf (string3); return 0; }
char string1[] = "A string declared as an array.\n";
This is usually the best way to declare and initialize a string. The
character array is declared explicitly. There is no size declaration
for the array; just enough memory is allocated for the string, because
the compiler knows how long the string constant is. The compiler stores
the string constant in the character array and adds a null character
(\0
) to the end.
char *string2 = "A string declared as a pointer.\n";
The second of these initializations is a pointer to an array of
characters. Just as in the last example, the compiler calculates the
size of the array from the string constant and adds a null character.
The compiler then assigns a pointer to the first character of the
character array to the variable string2
.
Note: Most string functions will accept strings declared in
either of these two ways. Consider the printf
statements at the
end of the example program above -- the statements to print the
variables string1
and string2
are identical.
char string3[30];
Declaring a string in this way is useful when you don't know what the
string variable will contain, but have a general idea of the length of
its contents (in this case, the string can be a maximum of 30 characters
long). The drawback is that you will either have to use some kind of
string function to assign the variable a value, as the next line of code
does ( strcpy(string3, "A string constant copied in.\n");
), or
you will have to assign the elements of the array the hard way,
character by character. (See String library functions, for more information
on the function strcpy
.)