|
There is one more piece of information to determine the string:
|
|
Example:
The string in the above figure is:
ASCII codes: 72 101 108 108 Characters: H e l l |
|
Example:
The string in the above figure is:
ASCII codes: 72 101 108 108 Characters: H e l l |
NOTE: the sentinel '\0' is not part of the string
"content of the string" |
Example:
"Hello World !" |
This expression will return the address of the first character of the string
char s[] = "content of string"; |
By omitting the SIZE of the array from the definition, C++ will create an array of the size that is given in the data initialization
Example:
char s[] = "Hello World !"; |
This will create an array of 14 bytes (13 letters and one more byte for the sentinel '\0')
Example:
char s[] = "Hello World !"; s[4] = ','; // s is now "Hell, World!" |
Example:
char *s = "Hello World !"; // CONSTANT string |
When you try to change the string, the program will crash
Example:
char *s = "Hello World !"; // String literal s[4] = ','; // CRASH !!! Cannot change a literal |
Example:
char s[10]; // s stores a string char *p; // Help variable used to copy string char *q = "Hello World !"; // Source string // Copy string q to string s p = s; // p points to receiving array while ( *q != '\0' ) *p++ = *q++; *p = '\0'; // Mark end of string |
char s[10]; // s stores a string char *p; // Help variable used to copy string char *q = "Hello World !"; // Source string // Copy string q to string s p = s; // p points to receiving array while ( (*p++ = *q++) != '\0' ); |
It takes advantage of the fact that the assignment expression "*p++ = *q++" in C/C++ returns the value assigned
|
Some example functions:
|