首页 技术 正文
技术 2022年11月21日
0 收藏 427 点赞 4,916 浏览 1897 个字

typedef 只对已有的类型进行别名定义,不产生新的类型;

#define 只是在预处理过程对代码进行简单的替换。

类比理解:

typedef  unsigned int  UINT32;  // UINT32 类型是unsigned int

UINT32 sum;                                 // 定义一个变量:int sum;

typedef  int  arr[3];                     // arr 类型是 int[3];(存放int型数据的数组)

arr a;                                              // 定义一个数组:int a[3];

同理:

typedef  void (*pfun)(void);         // pfun 类型是 void(*)(void)

pfun main;                                       // 定义一个函数:void (*main)(void);

在博客上看到一个经典的函数指针用例:

为保护原创作者的权益,以下例子代码不作修改:

<来源网址:http://www.cnblogs.com/shenlian/archive/2011/05/21/2053149.html>

#include<stdio.h>

typedef int (*FP_CALC)(int, int);

—————————————————————————————————————————————–其实就是函数指针的用法
下面这篇文章讲的很详细

http://blog.csdn.net/qll125596718/article/details/6891881
#include<stdio.h>
typedef void (*fun)(void) ;
char (*pFun)(int);
char glFun(int a)
{
return char(a);
}
int main()
{
pFun = glFun;
printf("%c\n",(*pFun)());
printf("%c\n",pFun());
return ;
}

第一行定义了一个指针变量pFun。首先我们根据前面提到的“形式1”认识到它是一个指向某种函数的指针,这种函数参数是一个int型,返回值是char类型。只有第一句我们还无法使用这个指针,因为我们还未对它进行赋值。

第二行定义了一个函数glFun()。该函数正好是一个以int为参数返回char的函数。我们要从指针的层次上理解函数——函数的函数名实际上就是一个指针,函数名指向该函数的代码在内存中的首地址

然后就是main()函数了,它的第一句您应该看得懂了——它将函数glFun的地址赋值给变量pFun。main()函数的第二句中“*pFun”显然是取pFun所指向地址的内容,当然也就是取出了函数glFun()的内容,然后给定参数为2。



在c语言中,定义一个结构体要用typedef ,例如下面的示例代码,Stack sq;中的Stack就是struct Stack的别名。

如果没有用到typedef,例如定义

struct test1{
int a;
int b;
int c;};test1 t;//声明变量

下面语句就会报错

struct.c:31:1: error: must use ‘struct’ tag to refer to type ‘test1’

test1 t;

^

struct

1 error generated.

声明变量时候就要用struct test1;这样就解决了

如果这样定义的话

typedef struct test3{
int a;
int b;
int c;
}test4;

test3 d;
test4 f;

此时会报错

struct.c:50:1: error: must use ‘struct’ tag to refer to type ‘test3’

test3 d;

^

struct

1 error generated.

所以要struct test3这样来声明变量d;

分析一下:

上面的test3是标识符,test4 是变量类型(相当于(int,char等))。

我们可以用struct test3 d来定义变量d;为什么不能用test3 d来定义是错误的,因为test3相当于标识符,不是一个结构体,struc test3 合在一起才代表是一个结构类型。

所以声明时候要test3时候要用struct test3 d;

typedef其实是为这个结构体起了一个新的名字,test4;

typedef struct test3 test4;

test4 相当于struct test3;

就是这么回事。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,910
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,435
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,250
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,061
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,693
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,731