三种: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'。
// 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;}这样输出的原因:结构体里面的每一个元素都占有一定的内存空间。而共用体占用其元素中最长的变量的那个类型的内存空间。其赋值是覆盖式的