C语言结构体讲解(一)

1.C语言为什么有结构体这个东西?

为了描述复杂个体,只用内置类型不能完全表述。

2.如何去定义结构体?
   struct + 结构体名
   {
      成员列表;
   };

struct Students
{
	char name[20];//名字,汉字占两个字节,这里只能输入9个汉字,后边还有'\0'
	int id;//学号
	char sex;//性别  1为男  0为女
	int age;//年龄
};

结构体定义好之后,它就和内置类型没有区分:

int a=10;
int *p=&a;
int arr[10]={1,2,3,4};

//对照之前学的去看结构体

struct Students stu1 = { "小王",12345,1,34 };//按顺序写
struct Students stu3 = {"lisa"};//结构体赋值一部分,剩余全为0.

struct Students* stup = &stu1;//指针
struct Students* stuq;

struct Students Stu_arr[10];//数组
struct Students Stu_brr[10] = { {"cai",12345,1,34},{"liu",23456,0,35} };

3.结构体套结构体

struct A
{
	int a;
	int b;
};
struct B
{
	int a;//不会与A中的a冲突,所属结构体不同
	struct A b;//ok,结构体套结构体
//思考下面写法可不可以
	struct A* c;                                        //ok
	struct B b;                                         //错误,编译器不知道预留多大内存
	struct B* b;                                        //ok,预留4个字节(32位)
};
//结构体A必须在结构体B的上方

4.如何去使用结构体?
  4.1结构体普通变量如何访问其成员;   C语言规定:结构体普通变量通过点访问
                注意: 结构体里的字符串要修改调用字符串拷贝函数strcpy,不能通过等于
  4.2结构体指针变量如何访问其成员;可以通过箭头的方式去访问   (*p).name == p->name

printf("%s ", stu1.name);//通过点访问
printf("%d ", stu1.id);
printf("%d ", stu1.sex);
printf("%d ", stu1.age);


struct Student* p = &stu1;
(*p).id = 76543;
strcpy_s((*p).name, "sunjian");//字符串拷贝函数修改结构体里字符串的值
p->sex = 0;

	printf("%s ", p->name);//printf("%s ", (*p).name);通过->访问
	printf("%d ", p->id);//printf("%d ", (*p).id);
	printf("%d ", p->sex);//printf("%d ", (*p).sex);
	printf("%d ", p->age);//printf("%d ", (*p).age);

结构体(二)讲解:结构体对齐,枚举与联合体,结构体和文件,接下来看tyepdef的使用:

1.typedef的使用
     typedef  类型  外号;//给一个类型取一个别名
     可以给外号再起一个外号

typedef unsigned long long int uint64;//将无符号位的long long 型另取了了一个外号叫uint64
uint64 b;//b的类型是long long

数组

//数组
typedef int arr[10];
arr brr;//int brr[10]

结构体

//结构体
struct Student
{
	char name[20];
	int age;
	char sex;
	char id;
	int Chine_score;
	int Math_score;
	int English_score;
	int sum;
};
typedef struct Student
{
	char name[20];
	int age;
	char sex;
	char id;
	int Chine_score;
	int Math_score;
	int English_score;
	int sum;
}Student;//相当于typedef struct Student Student(在分号里面)

typedef struct Student
{
	char name[20];
	char id[12];
	double score;
}Student,*pstudent;//相当于typedef struct Student Student,typedef struct Student* pstudent;

给函数指针起别名

//typedef int (*PMAX)(int,int)给函数指针起别名 

思考一个问题:可不可以给外号再起一个外号?

答案:是可以的

typedef int AAA;
typedef AAA BBB;
AAA a;
BBB b;
int c;//a,b,c都是int类型

那么思考:typedef int* Pint;和#define PINT int*有什么区别,一个是typedef,一个是宏变量

Pint p, q;//两个都是int*类型
PINT p, q;//p是int*,q是int类型
//因为宏就是简单的替换,PINT P,q;相当于int* p,q,即int* p,int q;
//而Pint p,q;相当于int *p,int *q

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值