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

用到取指针中的值

相关推荐
a0023450014 分钟前
python类型转换&深浅拷贝
开发语言·python
2301_7665360533 分钟前
调试无痛入手
开发语言·前端
rjszcb36 分钟前
JSON格式,C语言自己实现,以及直接调用库函数(一)
c语言·json
+72038 分钟前
Java 的 HttpClient 中使用 POST 请求传递参数
java·开发语言
@大迁世界2 小时前
构建 Next.js 应用时的安全保障与风险防范措施
开发语言·前端·javascript·安全·ecmascript
水瓶丫头站住3 小时前
Qt中QRadioButton的样式设置
开发语言·qt
xinghuitunan3 小时前
时间转换(acwing)c/c++/java/python
java·c语言·c++·python