结构体中的成员如果是字符数组,有几种赋值方式?

如题所述

三种:
1
按字符赋值。
如结构体变量为a,
成员为字符数组s[10];
那么可以
for(i
=
0;
i
<
10;
i
++)
a.s[i]
=
xxx;
xxx可以是任意字符。比如getchar(),即从终端读取。
2
用strcpy赋值。

strcpy(a.s,
"test");
就是将字符数组赋值为"test"。
3
用memcpy赋值。

memcpy(a.s,
"test
2",
3);
就是将a.s的前三个字符
赋值成't',
'e',
's'。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-01-25
你好!!!
原因很简单:s[1].name[50]="王佳芝";左边使用结构体的对象的成员,右边是字符串,要是那是存储在静态存储区的,这样赋值不符合语法:
应该使用strcpy()函数即可:
修改如下:
#include
#include
#define
st
struct
std
st
{
int
num;
char
name[7];
char
sex;
};
void
main()
{
st
s[10]={{5,"陈博",'m'}};
printf("%s\n",s[0].name);
s[1]=s[0];
strcpy(s[1].name,"王佳芝");
//s[1].name[50]="王佳芝";
//scanf("%s",s[1].name);
printf("%s\n",s[1].name);
}
结果:
陈博
王佳芝
press
any
key
to
continue
相似回答