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:

  1. Define with a character array:
char str[20]; // 定义一个长度为20的字符数组
  1. Define using character pointers:
char* str = "Hello World"; // 定义一个指向字符串常量的字符指针
  1. Initialize with a character array.
char str[] = "Hello World"; // 定义一个字符数组,并用指定的字符串初始化

Please note:

  1. 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.
  2. When a character pointer is defined, the string constant it points to cannot be modified, otherwise it will result in undefined behavior.
  3. 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.
bannerAds