数据结构(c语言)-- struct的用法

示例1:

/*
	如何使用结构体
			两种方式:
				struct Student st = {1000, "zhangsan", 20};
				struct Student * pst = &st;
				
				1.
					st.sid
				2. 
					pst->sid
					pst所指向的结构体变量中的sid这个成员		

*/

# include <stdio.h>
# include <string.h>

struct Student
{	
	int sid;
	char name[200];
	int age;
}; //分号不能省

int main(void)
{
	struct Student st = {1000, "zhangsan", 20};
	//st.sid = 99;  //第一种方式

	struct Student * pst;
	pst = &st;
	pst->sid = 99;  //第二种方式  pst->sid 等价于 (*pst).sid  而(*pst).sid等价于 st.sid,  所以pst->sid 等价于 st.sid

	return 0;
}

示例2:

# include <stdio.h>
# include <string.h>

struct Student
{	
	int sid;
	char name[200];
	int age;
}; //分号不能省

int main(void)
{
	struct Student st = {1000, "zhangsan", 20};
	printf("%d  %s  %d\n", st.sid, st.name, st.age);

	st.sid = 99;
	//st.name = "lisi";  //error
	strcpy(st.name, "lisi");
	st.age = 22;
	printf("%d  %s  %d\n", st.sid, st.name, st.age);

	//printf("%d %s %d\n", st);  //error
	return 0;
}

示例3:

#include<stdio.h>
#include<string.h>

typedef struct transcript		//定义结构体 
{
	int code;
	char name[20];
	int goals;
}TS;						//定义该结构体的第二个名字为TS  
int main(){

	TS ts;
	TS *zzr;				//定义结构体指针 *zzr 
	zzr = &ts;				//取ts的物理地址   zzr只能存储物理地址,不能存储物理地址的数值 
	zzr->code = 20187629;			//通过物理地址修改ts实参内的参数 
	strcpy(zzr->name,"小明");		//参数为字符时  需要使用strcpy()进行负值 
	(*zzr).goals =  100;
	printf("%s的学号是%d,这次考试成绩为%d分。\n",zzr->name,zzr->code,zzr->goals);	
	printf("zzr的物理地址是:%d",&zzr);

	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值