Attempting to directly assign values to string type members of a structIn the following code, when we try to directly use the “.” operator to access the string (character array) member in the struct and assign a value, the compiler will prompt:assignment to expression with array type, which translates to assigning a value to an expression with array type. For example, the following code:
#include <stdio.h>
struct Flower{
char name[20];
} rose;
int main(){
rose.name = "玫瑰";
return 0;
}
Why is this the case?The reason:The member name in the Flower struct type is a char array. In C, this is an array name, which is a pointer to the first element of the name array and is a constant that cannot be directly modified or assigned. This is different from char a[] = “hello”, which is allowed as it is an initialization of a character array.For example, in the following code, reassigning the array a to Lilly is also not allowed:
int main(){
char a[] = "Rose";
a = "Lilly";
return 0;
}
So how can we assign values to the array of a struct?That is, how can we reassign the memory address pointed to by an array name (constant pointer)? We can use the strcpy() function from the string.h header file. For example, the following sample code:
#include <stdio.h>
#include <string.h>
struct Flower{
char name[20];
} rose;
int main(){
strcpy(rose.name, "Rose");
printf("The name of rose is: %s\n", rose.name);
char a[] = "玫瑰";
strcpy(a, "牡丹");
printf("The name of a has been changed to: %s\n", a);
return 0;
}
The code compiles and runs, producing the output:
rose的名称为:Rose
a的名称被修改为:牡丹
Disclaimer: The content is for reference only and does not guarantee accuracy.