标签:
C语言中结构体的定义和初始化有以下几种方法:
1. 定义的同时初始化:
struct Person{
char name[20];
int age;
float score;
} p = {"lilei",20,80}; //局部初始化:p = {.age=20,.score=80};
或者
typedef struct {
char name[20];
int age;
float score;
}Person;
Person person = {"lilei",20,80};
//或者局部初始化
Person person2 = {.age=20,.score=80};
2. 定义之后再对结构的成员单独初始化:
struct Person{
char name1[20];
char *name2;
int age;
float score;
} p;
// p.name1 = "lilei";//错误用法
strcpy(p.name1, "lilei");//正确用法
p.name2 = "lilei";
p.age = 20;
p.score = 80;
3. 定义之后,初始化时进行强制类型转换:
struct Person{
char name[20];
int age;
float score;
} p;
//p = {"lilei",20,80}; //错误写法
p = (struct Person){"lilei",20,80};
4.定义之后,另外初始化一个相同结构并赋值给它:
struct Person{
char name[20];
int age;
float score;
} p;
struct Person p1 = {"lilei",20,80};
p = p1;
标签:
原文地址:http://www.cnblogs.com/lchuanmei/p/4375477.html