对于这个typedef,你可以从右到左阅读声明,所以在
typedef int pipe_t[2];
你有
-
[2] 表示它是 2 个数组。位置 [0] 和 [1]
-
pipe_t 是变量(类型)名称
-
int 表示 pipe_t[2] 是 2 个 int 的数组
-
typedef 说它实际上是一种类型——用户定义类型的别名,表示 2 个 int 的数组。
运行这个程序
#include<stdio.h>
int main(int argc, char** argv)
{
typedef int pipe_t[2];
printf("{typedef int pipe_t[2]} sizeof(pipe)_t is %d\n",
sizeof(pipe_t));
pipe_t test;
test[1] = 2;
test[0] = 1;
printf("pair: [%d,%d]\n", test[0], test[1]);
// with no typedef...
int (*another)[2];
another = &test;
(*another[0]) = 3;
(*another)[1] = 4;
printf("{another} pair: [%d,%d]\n", (*another)[0], (*another)[1]);
pipe_t* piped= &test;
printf("{Using pointer} pair: [%d,%d]\n", (*piped)[0], (*piped)[1]);
return 0;
};
你会看到
{typedef int pipe_t[2]} sizeof(pipe)_t is 8
pair: [1,2]
{another} pair: [3,4]
{Using pointer} pair: [3,4]
您会看到pipe_t 的大小为 8 个字节,对应于 x86 模式下的 2 个int。您可以将test 声明为pipe_t 并将其用作int 的数组。并且指针的工作方式相同
我添加了要在没有这种 typedef 的情况下使用的代码,因此我们看到使用 typedef 使其更易于阅读。