C typedef int pipe_t[2]的含义是什么;?
有人能用一种非常简单的方式向我解释一下这些代码行的含义吗C typedef int pipe_t[2]的含义是什么;?,c,malloc,typedef,sizeof,atoi,C,Malloc,Typedef,Sizeof,Atoi,有人能用一种非常简单的方式向我解释一下这些代码行的含义吗 typedef int pipe_t[2]; pipe_t *piped; int L; L = atoi(argv[2]); piped = (pipe_t *) malloc (L*sizeof(pipe_t)); 管道类型为“2整数数组” 变量piped是指向此类数组的指针 L是从命令行分配的整数 指针piped被指定为指向一个足够大的内存块,以容纳上述类型的L数组 对于此typedef,您可以从右到左阅读声明,因此 typ
typedef int pipe_t[2];
pipe_t *piped;
int L;
L = atoi(argv[2]);
piped = (pipe_t *) malloc (L*sizeof(pipe_t));
- 管道类型为“2整数数组”
- 变量
是指向此类数组的指针piped
是从命令行分配的整数L
- 指针
被指定为指向一个足够大的内存块,以容纳上述类型的piped
数组L
typedef int pipe_t[2];
你有
说它是一个2的数组。位置[0]和[1][2]
是变量(类型)名称pipe\t
表示int
是一个由2个pipe\u t[2]
int
说它实际上是一个类型-用户定义类型的别名,表示2typedef
的数组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;
};
您可以看到,pipe\u t
的大小为8个字节,对应于x86模式下的2个int
。您可以将test
声明为pipe\u t
,并将其用作int
的数组。指针的工作方式也是一样的
我添加了不使用此类typedef的代码,因此我们看到,使用typedef可以使读取更清晰。大概是为了从调用中捕获值。如果我删除了第一行代码,下面的内容应该如何更改?如果您理解
int pipe_t[2]
可以(声明一个包含2个整数的数组的对象),然后添加typedef
意味着单词pipe\u t
是第一个版本中pipe\u t
的类型的替代名称如果我删除了第一行代码,下面的内容应该如何更改?如果没有typedef,使用该类型的其他行变得更加复杂。例如,第二个必须是int(*管道)[2]代码>如果我删除了第一行代码,下面的内容应该如何更改?我不明白你想说什么:(如果删除typedef,则必须替换使用它的所有行。它只是一个别名。您应该这样声明它们:int(*other)[2];
和类似(*other)[0]的引用。)= 3;我把它添加到上面的代码中,这样你就可以看到2种可能性,也可以看到用于解释C和C++中声明的螺旋规则的可能性。你可以找到其他的引用它的问题。你的开头声明“在C中读从右到左的声明”有点简单。
{typedef int pipe_t[2]} sizeof(pipe)_t is 8
pair: [1,2]
{another} pair: [3,4]
{Using pointer} pair: [3,4]