There are several forms of defining strings in C: string constant, char array, char pointer
1. String constant
That is: located in a pair of double brackets any character. The characters in double quotes plus the end mark \0 character automatically provided by the compiler are stored in memory as a string
. For example: printf("%s","hello"); //"hello"
If there is no interval between string literals or the interval is a space character, ANSI C will concatenate them. Example:
char greeting[50] = "hello,and" "how are" "you";
Equivalent to:
char greeting[50] = " hello,and how are you";
String constants belong to the static storage class. Static storage means that if a string constant is used in a function, even if the function is called multiple times, only one copy of the string will be stored during the entire running process of the program. The entire quoted content serves as a pointer to the location where the string is stored. This is similar to using the array name as a pointer to the storage location of the array.
2. String array and its initialization
Initialization example:
char m[40] = "hello,world"; //Must be specified when defining a string array Array size (integer constant), when specifying the size, make sure the array size is one larger than the predetermined size, because the compiler will automatically add '\0'.
// Excess element will be initialized to '\ 0'
##char m = {'h', 'e', 'l', ' \0'}; //Pay attention to the null character that marks the end. Without it, you will get only a character array instead of a string
3. Use the char pointer to define the string
The compiler will regard the array name m as a synonym for the address of the first element of the array &m[0], where m is an address constant. You can use m+1 to identify the next element in the array, but you cannot use ++m. The increment operator can only be used before variables, not before constants.
m[40] is allocated an array of 40 elements in computer memory (each element corresponds to a character, and there is an additional element corresponding to the terminating null character '\0'). Each element is initialized to the corresponding character.
The above is the detailed content of Definition methods and explanation examples of strings in C. For more information, please follow other related articles on the PHP Chinese website!