C语言学习(十四)—typedef学习

C语言学习(十四)—typedef学习

一、前言

本文用来记录自己的学习过程,主要是C语言关键词typedef的学习。

typedef是c语言的关键字
作用是为一种数据类型定义一个新名字
这里的数据类型包括内部数据类型(int,char等)和自定义的数据类型(struct等)
和struct来匹配为了代码编写简洁和普通类型匹配,通过名字来获取信息

typedef和自定义结构体struct配合使用时, 常常进行另外命名的同时给出模板指针,更便于使用。

二、示例

#include <stdio.h>
#include <stdlib.h>

/*
	typedef
    typedef是c语言的关键字
    作用是为一种数据类型定义一个新名字
    这里的数据类型包括内部数据类型(int,char等)和自定义的数据类型(struct等)
    
    和struct来匹配为了代码编写简洁
    和普通类型匹配,通过名字来获取信息
*/


// 单片机开发中,寄存器为8、16、32位
typedef unsigned char u_int8;//(0 255)
typedef unsigned short int u_int16;
typedef unsigned int u_int32;

typedef struct Student
{
	int score;
    char *name;
}STU,*PSTU; //将自定义的结构体struct Student模板命名为STU 给出模板指针*PSTU

int main()
{
	u_int8  data0 = 10;
    u_int16 data1 = 11;
    u_int32 data2 = 22;
    printf("%d %d %d\n",data0,data1,data2);
    
	//使用名称
	STU stu;
    stu.score=99;
    printf("stu_score=%d\n",stu.score);
    //使用指针
    PSTU pstu;
    pstu=(PSTU)malloc(sizeof(STU));
    pstu->score=100;
    printf("pstu_score=%d\n",pstu->score);
    //使用指针但不用typedef
    struct Student* pstu1;
    pstu1=(struct Student *)malloc(sizeof(struct Student));
    pstu1->score =88;
    printf("pstu1_score=%d\n",pstu1->score);   
    
	system("pause");
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值