How do you declare a string in the C language?
In C language, strings can be defined using character arrays. A character array is a fixed-size array made up of characters, used to store each character of a string. One common method of defining strings is by using character arrays, as shown below:
char str[20]; // 定义一个大小为20的字符数组来存储字符串
// 或者可以直接在定义时给字符数组赋值
char str[] = "Hello World"; // 定义一个字符数组并赋值为 "Hello World"
In C language, strings are represented as character arrays, ending with the character ‘\0’. ‘\0’ is referred to as the null character or string terminator, used to indicate the end of the string. Therefore, in order to store a string in a character array, the size of the array must be one greater than the length of the string in order to leave space for ‘\0’.
Another way to represent strings is to use pointers that point to character arrays. For example:
char *str = "Hello World"; // 使用指针指向字符数组
This method stores the string in the static storage area and uses a pointer to point to the first character of the string. It is important to note that strings defined using the pointer method are not editable because string constants are stored in a read-only memory area. To modify a string, it should be defined using a character array.