How to assign values to a character array in C language?

In C language, you can assign values to character arrays using the following method:

  1. By using the assignment operator (=), you can directly assign a string to a character array. For example:
char str1[10];
str1 = "Hello"; // 错误,数组名不能直接赋值

This approach is incorrect because array names cannot be directly assigned. However, you can use the strcpy function to copy a string into a character array.

char str1[10];
strcpy(str1, "Hello"); // 将字符串"Hello"复制到str1中
  1. Assigning values one by one: You can use the subscript operator ([]) to assign values to a character array one at a time. For example:
char str1[10];
str1[0] = 'H';
str1[1] = 'e';
str1[2] = 'l';
str1[3] = 'l';
str1[4] = 'o';
str1[5] = '\0'; // 字符数组以空字符结尾,表示字符串的结束
  1. Initializing using string constants: You can directly initialize a character array with string constants when defining it. For example:
char str1[10] = "Hello"; // 将字符串"Hello"初始化到str1中

Please make sure the size of the character array is large enough to hold the content of the string (including the null character at the end).

  1. Assign values to a character array using a looping structure, such as a for loop, one by one. For example:
char str1[10];
for (int i = 0; i < 5; i++) {
    str1[i] = 'a' + i;
}
str1[5] = '\0'; // 字符数组以空字符结尾

The above are several commonly used methods for assigning values to character arrays, and you can choose the appropriate method based on specific needs.

bannerAds