zl程序教程

您现在的位置是:首页 >  硬件

当前栏目

C语言typedef创建变量/指针别名 | 使用结构体指针节省内存

内存C语言变量 使用 创建 结构 指针 别名
2023-06-13 09:13:10 时间

一、使用typedef创建结构体变量

区分

一个是给结构体变量起别名,一个是给结构体指针起了别名

typedef struct Student{
	int age;
	int id;
}Student, * Studentp;

写法

创建一个Student结构体变量,常规写法:

struct Student student1; // 不用typedef

但现在,可以直接这样创建:

Student student1; // 若使用typedef 

分析: typedef相当于给结构体 struct Student 定义了一个别名,这个别名叫 Student 。 所以可以直接用Student来声明一个结构体变量

二、 关于结构体成员的调用

若使用 struct Student student1;或者使用了别名创建结构体后访问成员都要使用‘.’运算符

struct Student student1;
student1.age;
/*typedef部分省略*/
Student student1;
student1.age;

如果用Studentp来创建变量呢?

需要分配内存或者让指针指向结构体

Studentp student1; // 注意是Studentp,创建的是结构体指针
student1 = (studentp)malloc(sizeof(Student)); // 指针,要么你主动分配内存,要么你把这个指针指向一个已有的结构体~
student1->age; // 那这里student1就是一个结构体变量的指针,要用->访问

相当于你Studentp创建的是一个结构体的指针,那访问也需要用指针的形式访问!

三、结构体成员也有指针类型情况

typedef struct Student{
	int* age;  //也就是age是int*类型,age是指针。
	int id;
}Student, * Studentp;

那这个时候,就必须要对指针 age 也要初始化!

#include <stdio.h>
#include <stdlib.h>
typedef struct Student {
	int* age;
	int id;
}Student, * Studentp;

int main() {
	Studentp A ; // A是指向某一 struct Student 的一个指针
	A = (Studentp)malloc(sizeof(Student)); // 指针 A 初始化
	A->age = (int*)malloc(sizeof(int)); // A->age,age也是一个指针,需要初始化
	*(A->age) =1 ; // A->age是指针,访问变量需要*(A->age)!!!!
	printf("%d", *(A->age)); // 这里也是,如果不整体加*,就会输出地址
	return 0;
}

四、关于为什么结构体成员也有指针类型

原因

其实是方便内存对齐,不造成内存浪费。 示例

typedef struct Student {
	char id; // 这里用了 char 类型
	int age;
}Student, * Studentp;

char第0个的话。age就从第4个内存开始了。 相当于第1,第2,第3个内存是空的,浪费了内存。 所以可以使用指针(默认占4个字节)

不管是任何类型的指针,其字节数都是4字节。

typedef struct Student {
	char* id; // 这里用了 char* 类型
	int age;
}Student, * Studentp;
1234

char*,占4个字节,内存不浪费。