How can you assign values to a string array in the C language?
In C language, you can assign values to string arrays using either the strcpy function or direct assignment.
- Use the strcpy function:
#include <stdio.h>
#include <string.h>
int main() {
char str1[10];
char str2[10] = "Hello";
strcpy(str1, str2);
printf("str1: %s\n", str1);
printf("str2: %s\n", str2);
return 0;
}
- Direct assignment方式:
#include <stdio.h>
int main() {
char str1[10];
char str2[10] = "Hello";
for(int i = 0; i < 6; i++) {
str1[i] = str2[i];
}
str1[6] = '\0'; // 添加字符串结束符
printf("str1: %s\n", str1);
printf("str2: %s\n", str2);
return 0;
}
Both of the methods mentioned above can be used to assign values to string arrays, depending on the specific situation, you can choose which method to use.