[英]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));
pipe_t
is "array of 2 ints"pipe_t
是“2 个整数的数组”piped
is a pointer to such arrays.piped
是指向此类 arrays 的指针。L
is an integer, assigned from the command line L
是 integer,从命令行分配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.