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的地址

用到取指针中的值

相关推荐
武子康4 小时前
Java-171 Neo4j 备份与恢复 + 预热与执行计划实战
java·开发语言·数据库·性能优化·系统架构·nosql·neo4j
怪兽20145 小时前
fastjson在kotlin不使用kotlin-reflect库怎么使用?
android·开发语言·kotlin
ClearLiang5 小时前
Kotlin-协程的挂起与恢复
开发语言·kotlin
彭同学学习日志5 小时前
Kotlin Fragment 按钮跳转报错解决:Unresolved reference ‘floatingActionButton‘
android·开发语言·kotlin
海域云赵从友5 小时前
破解跨境数据传输瓶颈:中国德国高速跨境组网专线与本地化 IP 的协同策略
开发语言·php
咚咚王者5 小时前
人工智能之编程进阶 Python高级:第九章 爬虫类模块
开发语言·python
深蓝海拓5 小时前
使matplot显示支持中文和负号
开发语言·python
syt_biancheng6 小时前
Day3算法训练(简写单词,dd爱框框,3-除2!)
开发语言·c++·算法·贪心算法
864记忆7 小时前
Qt Network 模块中的函数详解
开发语言·网络·qt
864记忆7 小时前
Qt Sql 模块中的函数详解
开发语言·网络·qt