【问题标题】:What is the meaning of typedef int pipe_t[2];?typedef int pipe_t[2]; 是什么意思?
【发布时间】:2023-03-18 09:20:02
【问题描述】:

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

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

【问题讨论】:

  • 如果您了解int pipe_t[2]; 会做什么(声明一个由 2 个整数组成的数组的对象),那么添加 typedef 意味着单词 pipe_t 是 @987654325 类型的替代名称@曾在第一个版本中
  • 如果我删除了第一行代码,下面应该如何改变?
  • 如果没有 typedef,使用该类型的其他行会变得更加复杂。例如,第二个必须是 int (*piped)[2];

标签: c malloc typedef sizeof atoi


【解决方案1】:
  • 类型pipe_t 是“2 个整数的数组”
  • 变量piped 是指向此类数组的指针。
  • L 是一个整数,从命令行分配
  • 指针piped 被分配指向一个足够大的内存块,以容纳上述类型的L 数组。

【讨论】:

  • 大概是从pipe()调用中获取值。
  • 如果我删除了第一行代码,下面应该如何改变?
【解决方案2】:

对于这个typedef,你可以从右到左阅读声明,所以在

typedef int pipe_t[2];

你有

  • [2] 表示它是 2 个数组。位置 [0] 和 [1]
  • pipe_t 是变量(类型)名称
  • int 表示 pipe_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;
};

你会看到

{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 使其更易于阅读。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-03
  • 1970-01-01
  • 1970-01-01
  • 2011-04-28
  • 2023-03-10
  • 1970-01-01
相关资源
最近更新 更多