struct typename(结构体名称)
{
members;(成员变量)
};
一、初始化
(1)
#include<stdio.h>
#include<string.h>
struct Contact
{
int id;
char name[16];
char *phone;
};
int main()
{
struct Contact a ;
a.id = 200;
strcpy(a.name,"xiaoming"); //字符数组赋值必须使用strcpy()函数
a.phone = "090001"; // 字符串指针 可以使用 a.phone 进行赋值
printf("%d %s %s", a.id, a.phone, a.name);
return 0;
}
(2)
也可以
struct Contact a={200,"xioaming","090001"};
进行赋值
(3)
#include<stdio.h>
#include<string.h>
struct Contact
{
int id;
char name[16];
char *phone;
}a; //也可在结构体后直接创建结构体对象
int main()
{
a.id = 10;
...
return 0;
}
二、指针
struct Contact
{
int id;
char name[16];
char *phone;
};
int main()
{
struct Contact a={200,"xioaming","090001"};
p=&a;
printf("%d %s %s", p->id, p->phone, p->name); //p->id 实际上等于 (*p).id
}
三、做函数参数
void get(struct Contact *p,int a)
{
p->id = 200;
}
四、匿名struct
struct
{
char *name;
int num;
}dog;
int main()
{
dog.name = "das";
dog.num = 23;
}
该方法创建的结构体没有名称 只有单独的一个对象 dog
因此该结构体只能使用一次
五、结构体做成员
(1)
#include<stdio.h>
#include<string.h>
struct Contact
{
int id;
char name[16];
char *phone;
struct Dog dog;
};
struct Dog
{
char *name;
int num;
};
int main()
{
struct Contact a;
a.dog.name ="sad";
a.dog.num = 3;
return 0;
}
(2)
#include<stdio.h>
#include<string.h>
struct Contact
{
int id;
char name[16];
char *phone;
struct Dog dog;
};
struct Dog
{
char *name;
int num;
};
int main()
{
struct Contact a;
struct Contact *p;
p = &a;
p->dog.name = "sad";
p->dog.num = 233;
return 0;
}