是否有任何手动方法来初始化struct中的字符串?我曾经使用strcpy函数初始化struct中的字符串,例如:
typedef struct {
int id;
char name[20];
int age;
} employee;
int main()
{
employee x;
x.age=25;
strcpy(x.name,"sam");
printf("employee age is %d \n",x.age);
printf("employee name is %s",x.name);
return 0;
}
最佳答案
严格地说
strcpy(x.name,"sam");
不是初始化。
如果要讨论初始化,可以按以下方式进行
employee x = { .name = "sam", .age = 25 };
或
employee x = { .name = { "sam" }, .age = 25 };
这相当于以下初始化
employee x = { 0, "sam", 25 };
或
employee x = { 0, { "sam" }, 25 };
或者,您甚至可以使用
employee
类型的复合文本来初始化对象x
,尽管这不是有效的。否则,如果不是初始化而是对结构的数据成员的赋值,那么实际上您必须至少使用
strcpy
或strncpy
。关于c - 如何在不使用strcpy函数的情况下初始化struct中的字符串?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45777154/