C语言 || typedef

typedef:给类型取一个别名

使用原因:起别名的目的不是为了提高程序的运行效率,而是为了编码方便
语法格式typedef oldname newname

例如:

  1. 给结构体起别名
typedef struct stu {
int n;
char ch;
float m;
}list;
struct stu a;
//等价于
list a;

2.给指针取别名

typedef int* n;
n a;
//等价于
int* a;

3.给函数指针起别名

typedef int (*ptr)(int int);
ptr a;

4.为数组起别名

typedef  int ARRAY20[20];
ARRAY20 a,b,c;
//等价于
int a[20],b[20],c[20];
//二维数组
typedef int (*ptr)[20];
//表示一个类型为int*[20],
ptr a;
//等价于
int (*ptr1)[20] a;

5.给一种类型起别名

typedef int a;
a ch;
//等价于
int ch;

给指针起别名的例子:

#include <stdio.h>

typedef char (*ptr)[20];
typedef int (*ptr1)(int int);

int max(int a,int b)
{
  return a>b?a:b;
}

char ch[2][20]={"C Pramgram",
                 "Hello World"}
;

int main()
{
   ptr sh=ch;
   ptr1 zh=max;
   int i;
   printf("%d\n",(*sh)(10,20));
   for(i=0;i<2;i++)
   {
     printf("%s\n",(*zh+i));
   }
   return 0;
}

typedef和define的区别

  1. 可以使用其他类型说明符对宏类型名进行扩展,但对typedef所定义的类型名却不能这样做。
  2. 在连续定义几个变量的时候,typedef能够保证定义的所有变量均为同一类型,而define则无法保证。例如:
#define PTR_INT int *

PTR_INT p1, p2;
//p1,p2类型不同,p1代表int* p1,p2代表int p2

猜你喜欢

转载自blog.csdn.net/weixin_44594976/article/details/89305882
今日推荐