typedef int pipe_t [2];是什么意思?

问题描述

谁能以一种非常简单的方式向我解释这些代码行的含义。

typedef int pipe_t[2];
pipe_t *piped; 
int L; 
L = atoi(argv[2]);
piped = (pipe_t *) malloc (L*sizeof(pipe_t));

解决方法

  • 类型pipe_t是“ 2个整数的数组”
  • 变量piped是指向此类数组的指针。
  • L是一个整数,从命令行分配
  • 指针piped被分配为指向足以容纳上述类型的L数组的内存块。
,

对于这种typedef,您可以从右到左读取声明,因此在

typedef int pipe_t[2];

你有

  • [2]说它是2的数组。位置[0]和[1]
  • pipe_t是变量(类型)名称
  • intpipe_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,(*another)[0],(*another)[1]);

    pipe_t* piped= &test;
    printf("{Using pointer} pair: [%d,(*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使其可读性更强。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...