1. 基础
定义:用户自定义的数据类型,在结构体中可以包含若干不同数据类型(也可以相同)的成员变量,使这些数据项组合起来反映某一个信息。
格式:
struct 结构体名
{
数据类型 成员变量1;
数据类型 成员变量2;
数据类型 成员变量3;
};
2. 结构体变量
(1)概念:通过结构体类型定义的变量
(2)格式:struct 结构体名 变量名;
① 先定义结构体类型,在定义结构体变量
struct 结构体名
{
数据类型 成员变量1;
数据类型 成员变量2;
数据类型 成员变量3;
};
struct 结构体名 变量名;
② 定义结构体的同时,定义结构体变量
struct 结构体名
{
数据类型 成员变量1;
数据类型 成员变量2;
数据类型 成员变量3;
}变量名;
③ 缺省结构体名定义结构体变量
struct
{
成员变量1;
成员变量2;
成员变量3;
}变量名;
3. 赋值
(1)定义变量时,直接用大括号赋值
#include <stdio.h>
struct test
{
int id;
int age;
char name[32];
};
int main(int argc, char const *argv[])
{
struct test s = {
1,
18,
};
return 0;
}
(2)定义变量时未初始化,然后对变量单独赋值
#include <stdio.h>
#include <string.h>
struct test
{
int id;
int age;
char name[32];
};
int main(int argc, char const *argv[])
{
struct test s;
s.id = 1;
s.age = 18;
strcpy(s.name, "zhangsan");
return 0;
}
(3) 点等法赋值
#include <stdio.h>
#include <string.h>
struct test
{
int id;
int age;
char name[32];
};
int main(int argc, char const *argv[])
{
struct test s = {
.id = 1;
.age = 18;
};
return 0;
}
4. 访问
通过 . 访问:结构体变量名.成员变量名
#include <stdio.h>
#include <string.h>
struct test
{
int id;
int age;
char name[32];
};
int main(int argc, char const *argv[])
{
struct test s;
scanf("%d %d %s", &s.id, &s.age, s.name);
printf("%d %d %s\n", s.id, s.age, s.name);
return 0;
}
5. 重定义typedef
typedef int size_t;
typedef int* int_p;
int a;====size_t a;
结构体的数据类型名字太长,重新取个别名;
typedef struct ikun
{
}KK;
1.定义的同时重定义
2. 先定义,再重定义