How can we initialize a string array in the C language?

There are several ways to initialize a string array in the C language.

  1. Initialize character by character: You can enclose them in curly brackets and assign each character to each element of the array individually. Here is an example code:
char str[5] = {'H', 'e', 'l', 'l', 'o'};
  1. String constant initialization: You can directly assign a string constant to an array. Here is an example code:
char str[] = "Hello";
  1. Assigning character arrays: You can assign an already existing character array to another character array. Example code is as follows:
char str1[] = "Hello";
char str2[6];
strcpy(str2, str1);

It should be noted that when initializing with string constants, the system automatically adds a null character ‘\0’ at the end of the string to indicate the end. However, when initializing character by character or assigning a character array, you need to manually add the null character to indicate the end of the string.

bannerAds