Initializing Strings

Because character arrays are so widely used as strings, there are easier ways to initialize strings:
char word[8] = "Celsius";
char word[]  = "Celsius";
char word[8] = {'C','e','l','s','i','u','s','\0'};
All 3 initializations produce the same result:
           word (refers to the entire array)
           ¯	
word[0] ® C	
word[1] ® e	
word[2] ® l	
word[3] ® s	
word[4] ® i	
word[5] ® u	
word[6] ® s	
word[7] ® \0  NULL character	
Note that these are initializations of strings. You cannot do this:
char word[8];      // declare array of 8 chars
word = "Celsius";  // ERROR, assign to entire array

word[0] = 'C';     // must do it this way
word[1] = 'e';
word[2] = 'l';
word[3] = 's';
word[4] = 'i';
word[5] = 'u';
word[6] = 's';
word[7] = '\0';
Previous page
Next page

Back to Lesson 12 Index
Back to Outline