How to define strings in the C programming language?
In the C language, strings can be defined using character arrays. Strings are made up of a series of characters, with the null character ‘\0’ serving as the ending marker.
Here are some common ways to define strings:
- Define with a character array:
char str[20]; // 定义一个长度为20的字符数组
- Define using character pointers:
char* str = "Hello World"; // 定义一个指向字符串常量的字符指针
- Initialize with a character array.
char str[] = "Hello World"; // 定义一个字符数组,并用指定的字符串初始化
Please note:
- When defining a character array, it is necessary to specify enough length to accommodate the characters of the string as well as the terminating null character.
- When a character pointer is defined, the string constant it points to cannot be modified, otherwise it will result in undefined behavior.
- Both arrays of characters and pointers to characters can be utilized to perform operations with string-related library functions such as strlen, strcpy, strcmp, and so on.