C语言中什么时候用“->”

使用说明

"->"是C语言中的一个运算符,它用于访问结构体或者联合体中的成员,其左边是一个指向结构体或者联合体的指针,右边是需要访问的成员名。

举例说明

定义结构体

c 复制代码
# include <stdio.h>
# include <stdlib.h>
//#include <string.h>
//# include <string.h>
//*** 5 ***
struct student //类型
{ //类型内容
	char name[20];
	int age;

};
typedef struct {
	char name[20];
	int age;
}student2;

int main() {
	// 相当于int    相当于 a = 8;
	/* 	
	* int * arr;
	* arr是地址
	* *arr是值
	*/
	struct student stu1;  //stu1是结构体名字
	struct student stu2;
	struct student *stu3; //stu3是结构体地址  *stu3才是结构体的值
	struct student *stu4;

	student2 stu5;

	// 结构体变量 静态 分配内存
	stu3 = &stu1; // 等价,地址要用地址来赋值,"地址=地址"
	// 动态内存分配
	stu4 = (struct student*)malloc(sizeof(struct student));//分配内存 allocation memory
	// 直接赋值
	char* strcpy(char* dest, const char* src);

	strcpy(stu1.name, "zhangsan"); // 字符串复制
	//printf("stu1.name = %s\n", stu1.name);// 字符串本身内容
	//printf("stu1.name = %d\n", stu1.name);// 字符数组的首地址
	stu1.age = 18;
	stu5.age = stu1.age + 2;
	printf("stu5 age is %d\n\n", stu5.age);
	//printf("stu1.age = %d\n", stu1.age);
	printf("stu3's age is %d\n\n", stu3->age); // pointer structure variable   结构变量
	printf("stu3's name is %s\n", stu3->name);// 用箭头访问name的地址
	// memcpy
	void* memcpy(void* dest, const void* src, size_t n);

	memcpy(&stu2, &stu1, sizeof(struct student));
	printf("stu2.name = %s\n", stu2.name);
	printf("stu2.age = %d\n\n", stu2.age);
	memcpy(stu4, &stu1, sizeof(struct student)); // stu4 结构体指针不用&取地址符
	printf("stu4.name = %s\n", stu2.name);
	printf("stu4.age = %d\n\n", stu2.age); 

	printf("stu4 ->name %s\n", stu4->name); //   %s 输出字符串
	printf("stu4 ->age %d\n", stu4->age); // %d 输出整数类型
	return 0;
}

其中

c 复制代码
	printf("stu4 ->name %s\n", stu4->name); //   %s 输出字符串
	printf("stu4 ->age %d\n", stu4->age); // %d 输出整数类型

以及

c 复制代码
    printf("stu3's age is %d\n\n", stu3->age); // pointer structure variable   
    // 结构变量
	printf("stu3's name is %s\n", stu3->name);// 用箭头访问name的地址

用到取指针中的值

相关推荐
看海天一色听风起雨落2 分钟前
Python学习之装饰器
开发语言·python·学习
Want5958 分钟前
C/C++圣诞树①
c语言·开发语言·c++
老赵的博客19 分钟前
c++ 杂记
开发语言·c++
jimmy.hua22 分钟前
[C++刷怪笼]:set/map--优质且易操作的容器
开发语言·c++
w2sfot1 小时前
Passing Arguments as an Object in JavaScript
开发语言·javascript·ecmascript
郝学胜-神的一滴2 小时前
避免使用非const全局变量:C++中的最佳实践 (C++ Core Guidelines)
开发语言·c++·程序人生
搞一搞汽车电子2 小时前
S32K3平台eMIOS 应用说明
开发语言·驱动开发·笔记·单片机·嵌入式硬件·汽车
l1t2 小时前
轻量级XML读写库Mini-XML的编译和使用
xml·c语言·解析器
总有刁民想爱朕ha3 小时前
车牌模拟生成器:Python3.8+Opencv代码实现与商业应用前景(C#、python 开发包SDK)
开发语言·python·数据挖掘
小菜全3 小时前
uniapp新增页面及跳转配置方法
开发语言·前端·javascript·vue.js·前端框架