How to assign values to strings in the C language?

In the C programming language, strings can be assigned in the following way:

  1. Define a string with a character array, and then assign the string to the character array using the assignment operator. For example:
char str[10];
strcpy(str, "Hello");
  1. Define a string using a character pointer, then assign the address of the string to the character pointer using the assignment operator. For example:
char *str;
str = "Hello";
  1. Define a string using a character array and assign characters one by one. For example:
char str[10];
str[0] = 'H';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
str[5] = '\0'; // 字符串以空字符结尾

Please note:

  1. When defining a string using a character array, make sure the array is large enough to accommodate the string and the terminating null character.
  2. When defining a string with character pointers, the address of the string constant is constant and cannot be changed.
bannerAds