Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C typedef int pipe_t[2]的含义是什么;?_C_Malloc_Typedef_Sizeof_Atoi - Fatal编程技术网

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,您可以从右到左阅读声明,因此

typedef int pipe_t[2];
你有

  • [2]
    说它是一个2的数组。位置[0]和[1]
  • pipe\t
    是变量(类型)名称
  • int
    表示
    pipe\u 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;
};
您可以看到,
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]