简体   繁体   English

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

[英]What is the meaning of typedef int pipe_t[2];?

Can anyone explain to me in a very simple way the meaning of these lines of code.谁能用非常简单的方式向我解释这些代码行的含义。

typedef int pipe_t[2];
pipe_t *piped; 
int L; 
L = atoi(argv[2]);
piped = (pipe_t *) malloc (L*sizeof(pipe_t));
  • Type pipe_t is "array of 2 ints"类型pipe_t是“2 个整数的数组”
  • Variable piped is a pointer to such arrays.变量piped是指向此类 arrays 的指针。
  • L is an integer, assigned from the command line L是 integer,从命令行分配
  • Pointer piped is assigned to point to a block of memory large enough for L arrays of the type above. piped指针被分配指向 memory 块,该块足够大,足以容纳上述类型的L arrays。

For this typedef, you can read the declaration from right to left, so in对于这个 typedef,你可以从右到左阅读声明,所以在

typedef int pipe_t[2];

you have你有

  • [2] says it is an array of 2. Positions [0] and [1] [2]表示它是 2 个数组。位置 [0] 和 [1]
  • pipe_t is the variable (type) name pipe_t是变量(类型)名称
  • int says pipe_t[2] is an array of 2 int int表示pipe_t[2]是 2 个int的数组
  • typedef says that it is, in fact, a type — an alias for a user-defined type representing an array of 2 int . typedef说它实际上是一种类型——用户定义类型的别名,表示 2 个int的数组。

Run this program运行这个程序

#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;
};

And you see你看

{typedef int pipe_t[2]} sizeof(pipe)_t is 8
pair: [1,2]
{another} pair: [3,4]
{Using pointer} pair: [3,4]

And you see that pipe_t has a size of 8 bytes, corresponding to 2 int 's in x86 mode.您会看到pipe_t的大小为 8 个字节,对应于 x86 模式下的 2 个int And you can declare test as pipe_t and use it as an array of int .您可以将test声明为pipe_t并将其用作int数组。 And the pointer works the same way指针的工作方式相同

And I added the code to be used without such typedef, so we see that using a typedef makes it a bit cleaner to read.我添加了要在没有这种 typedef 的情况下使用的代码,所以我们看到使用 typedef 使它更易于阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM