Strings
An array is a data structure that contain a collection of data objects of the same data type.
A string is an array of characters terminated by the NULL character. It is a sequence of characters treated as a group.
C program uses delimited strings.
Some example strings:
- "filename"
- "output string"
Examples: integer, floating-point, character, Booleans, void, pointers, arrays, structures, unions, enumerations
Storing Strings and Characters
Note: A string literal is enclosed in double quotes
Differences between Strings and Character Arrays
The difference between string and character array is, the string character ends with the null character.
The character string has an array size of eleven. Hence, the string ends after 'y'. The remaining two columns are not a part of the array.
Character Literals and String Literals
A string literal is a sequence of characters enclosed in double quotes. It is also known as a string constant. A character literal is a sequence of characters enclosed in single quotes.
For example, the character string:
char s1 ="a"; //Takes two bytes of storage.
s1:
|
a
|
\0
|
On the other hand, the character, in single quotes:
char s2= 'a' ; //Takes only one byte of storage.
s2:
|
a
|
String Literal References
From the above program it is clear that when the array subscript in the printf is taken as '1', then the value 'e' is printed.
Declaring Strings
The string pointer is declared as a character. In order to display the array, the string 'pStr' should be initialized.
Hence, the memory location of the string must be allocated before the string can be used.
Initializing Strings
char my_message [20] = "Good Day"
The null character '\O' is added, at the end.
Another alternative:
char short_string [] = "Good Day"