C语言:给结构体取别名的4种方法

0 前言

在进行嵌入式开发的过程中,我们经常会见到typedef这个关键字,这个关键字的作用是给现有的类型取别名,在实际使用过程中往往是将一个复杂的类型名取一个简单的名字,便于我们的使用。就像我们给很熟的人取外号一样,就是便于我们的记忆和使用。

1 给结构体取别名的4种方法

1.1 定义结构体时取别名(1)

示例代码:

c 复制代码
typedef struct
{
    int x;
    int y;
} test1_t;

结果:给结构体取别名为test1_t。

这种方法最简洁,但存在一个问题,如果我们定义的结构体是一个链表则无法定义一个本身结构体类型的指针。

1.2 定义结构体时取别名(2)

示例代码:

c 复制代码
typedef struct t2
{
    int x;
    int y;
} test2_t;

结果:给结构体取别名为test2_t。

这种方法比上面那种略复杂,但可以定义一个本身结构体类型的指针。在结构体内定义本身结构体类型的指针的语句:struct t2 *x;

1.3 定义结构体完成后取别名(1)

c 复制代码
struct t3
{
    int x;
    int y;
};
typedef struct t3 test3_t;

结果:给结构体struct t3取别名为test2_t。

这种方法写得更加臃肿一些,不过结构看起来更加明朗。

1.4 定义结构体完成后取别名(2)

c 复制代码
struct t3
{
    int x;
    int y;
};
typedef struct t3 *test4_t;

结果:给struct t3取别名为*test4_t,相当于test4_t是struct t3型指针类型。

这种方法可以直接给结构体取一个指针别名类型,这样取别名后定义一个结构体指针变量语句为:test4_t x;

2 结果测试

将上述的操作方法放到一个源文件内,设置并打印结构体成员的值。测试代码如下:

c 复制代码
#include "stdio.h"

typedef struct
{
    int x;
    int y;
} test1_t;

typedef struct t2
{
    int x;
    int y;
} test2_t;

struct t3
{
    int x;
    int y;
};
typedef struct t3 test3_t;
typedef struct t3 *test4_t;


int main(void)
{
    test1_t test1;
    test2_t test2;
    test3_t test3;
    test4_t test4 = &test3;
    test1.x = 1;
    test1.y = 2;
    test2.x = 1;
    test2.y = 2;
    test3.x = 1;
    test3.y = 2;
    printf("test 1 ==> x : %d, y : %d\r\n", test1.x, test1.y);
    printf("test 2 ==> x : %d, y : %d\r\n", test2.x, test2.y);
    printf("test 3 ==> x : %d, y : %d\r\n", test3.x, test3.y);
    printf("test 4 ==> x : %d, y : %d\r\n", test4->x, test4->y);
    return 0;
}

测试结果:

相关推荐
小莞尔3 天前
【51单片机】【protues仿真】基于51单片机的篮球计时计分器系统
c语言·stm32·单片机·嵌入式硬件·51单片机
小莞尔3 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
liujing102329293 天前
Day03_刷题niuke20250915
c语言
第七序章3 天前
【C++STL】list的详细用法和底层实现
c语言·c++·自然语言处理·list
l1t3 天前
利用DeepSeek实现服务器客户端模式的DuckDB原型
服务器·c语言·数据库·人工智能·postgresql·协议·duckdb
l1t3 天前
利用美团龙猫用libxml2编写XML转CSV文件C程序
xml·c语言·libxml2·解析器
Gu_shiwww3 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
你怎么知道我是队长3 天前
C语言---循环结构
c语言·开发语言·算法
程序猿编码3 天前
基于 Linux 内核模块的字符设备 FIFO 驱动设计与实现解析(C/C++代码实现)
linux·c语言·c++·内核模块·fifo·字符设备
mark-puls3 天前
C语言打印爱心
c语言·开发语言·算法