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

用到取指针中的值

相关推荐
Y1rong2 小时前
C++ QT之记事本
开发语言·qt
diegoXie6 小时前
Python / R 向量顺序分割与跨步分割
开发语言·python·r语言
程序员小白条6 小时前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
liulilittle6 小时前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
失散136 小时前
Python——1 概述
开发语言·python
萧鼎6 小时前
Python 图像哈希库 imagehash——从原理到实践
开发语言·python·哈希算法
小小8程序员7 小时前
STL 库(C++ Standard Template Library)全面介绍
java·开发语言·c++
立志成为大牛的小牛7 小时前
数据结构——五十六、排序的基本概念(王道408)
开发语言·数据结构·程序人生·算法
老王熬夜敲代码7 小时前
C++中的atomic
开发语言·c++·笔记·面试
a努力。7 小时前
腾讯Java面试被问:String、StringBuffer、StringBuilder区别
java·开发语言·后端·面试·职场和发展·架构