结构体与结构体变量

本文探讨了在函数调用中使用结构体变量与结构体指针变量的区别。通过指针传递结构体参数能有效降低内存消耗,而直接传递结构体会增加开销。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、访问结构体变量的两种方式:见例一
第一种:stu.id = 1001;
第二种:pst->id = 99;
第二种用的的证明如下:
struct Student *pst;
pst = &stu; //pst指向了stu,所以*pst等价于stu
pst->id = 99; //pst->id 等价于 (*pst).id,而(*pst).id等价于stu.id;所以pst->id等价于stu.id。pst指向结构体中id这个成员。

2、结构体变量:见例二
结构体变量不能加减乘除,但是能相互赋值。

普通结构体变量和结构体指针变量作为函数参数的问题:指针变量本身占四个字节,若结构体变量作为参数,用指针传递参数可大大减少内存消耗。若以结构体的一个对象作为参数,则开销会增大。

例一
#include<stdio.h>
#include<string.h>
struct Student{
	int id;
	char name[20];
	int age;
};

int main() {
	struct Student stu = { 1000 , "lisi" , 20 };
	printf("%d  %s  %d\n", stu.id, stu.name, stu.age);
	//如何使用结构体
	//第一种方式
	stu.id = 1001;	
	strcpy_s(stu.name, "zhangsan");
	stu.age = 22;
	printf("%d  %s  %d\n", stu.id, stu.name, stu.age);
	//第二种方式
	struct Student *pst;
	pst = &stu;		//pst指向了stu,所以*pst等价于stu
	pst->id = 99;	//pst->id 等价于 (*pst).id,而(*pst).id等价于stu.id;所以pst->id等价于stu.id。
	//pst指向结构体中id这个成员
	return 0;
}

例二:
#include<stdio.h>
#include<string.h>
struct Student {
	int id;
	char name[20];
	int age;
};
void f(struct Student *pstu);
void g_1(struct Student stu);
void g_2(struct Student *pstu);
int main() {
	struct Student stu;	//已经为stu分配好了内存
	f(&stu);
	g_1(stu);		//加上记忆对齐至少28+个字节 ,耗内存
	g_2(&stu);		//指针变量只有4个字节大小
	return 0;
}
void f(struct Student *pstu) {
	(*pstu).id = 1001;
	strcpy_s(pstu->name, "zhangsan");
	pstu->age = 22;
}

void g_1(struct Student stu) {
	printf("%d  %s  %d\n", stu.id, stu.name, stu.age);
}
void g_2(struct Student *pstu) {
	printf("%d  %s  %d\n", pstu->id, pstu->name, pstu->age);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值