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

如题所述

三种:

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个回答  2012-05-16
1、声明结构体变量时用字符串常量初始化
2、用scanf的%s输入结构体变量的字符数组成员
3、用strcpy给结构体变量的字符数组成员复制进内容本回答被提问者采纳
第2个回答  2013-04-02
// 2013-04-02-001.cpp : 定义控制台应用程序的入口点。//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
typedef struct test
{
string strname;
int nid;
int age;
char sex[10];
unsigned int sn: 4;
} test_a,test_b[2];

typedef struct test2
{
string strname;
int nid;
int age;
char sex[5];
unsigned int sn: 4;
} test_a2;

union best
{
int number;
char name[10];
double value;

}pbest;

int _tmain(int argc, _TCHAR* argv[])
{
test_a *ptest=new test_a;
ptest->strname="中国人";
ptest->nid=300;
cout<<"test_a.name= "<<ptest->strname<<"\n"<<"test_a.nid= "<<ptest->nid<<endl;
test test_b[2]={
{"wj",18,30,"man"},
{"jack",28,40,"woman",88},
};
//test2 testa2={"kfc",28,40,"woman",88};
test2 testa2;
testa2.strname="kfc";
testa2.age=28;
testa2.nid=40;
strcpy(testa2.sex,"woman");//值超出数组范围
testa2.sn=2231;

cout<<"test_b.name= "<<test_b[0].strname<<endl;
cout<<"testa2.name= "<<testa2.strname<<endl;
cout<<"testa2.sex= "<<testa2.sex<<endl;
cout<<"testa2.sn= "<<testa2.sn<<endl;

pbest.number=30;//分别赋值
cout<<"pbest.number= "<<pbest.number<<endl;//分别输出
pbest.value=800;
cout<<"pbest.value= "<<pbest.value<<endl;
strcpy(pbest.name,"新中国");
cout<<"pbest.name= "<<pbest.name<<endl;

//best pbest={50,800,strcpy(pbest.name,"新中国")};

system("pause");
return 0;
}

这样输出的原因:结构体里面的每一个元素都占有一定的内存空间。而共用体占用其元素中最长的变量的那个类型的内存空间。其赋值是覆盖式的
相似回答