简体   繁体   English

将两个别名传递给typedef struct是什么意思?

[英]What does passing two aliases to `typedef struct` mean?

What does *B in the following code mean? 以下代码中的*B是什么意思? I understand this mixture between typedef and struct . 我理解typedefstruct之间的这种混合。 However, this *B is strange. 但是,这个*B很奇怪。

typedef struct Something
{
...
}
A, *B;

I saw multiple questions asking about mixing typedef with struct but non of them talked about this double definition. 我看到多个问题询问将typedefstruct混合使用,但是没有一个人谈论这个双重定义。

This is a less-common use case for the typedef keyword that allows you to define two or more type aliases in a single line. 这是typedef关键字的一种较不常用的用例,它允许您在一行中定义两个或多个类型别名。 Here, this says 在这里,这说

  • make an alias named A that represents the struct itself, and 创建一个别名A来代表struct本身,并
  • make an alias named B that represents a pointer to the struct . 创建一个名为B的别名,该别名表示指向struct的指针。

In that sense, it's similar to writing something like 从这个意义上讲,这类似于写类似

int A, *B;

Here, this declares an integer named A and a pointer to an integer named B . 在这里,它声明了一个名为A的整数和一个指向名为B的整数的指针。 The syntax here involving the * works very similarly to what's going on in the typedef statement, except that instead of introducing variables it's introducing types. 这里涉及*的语法的工作方式与typedef语句中的工作方式非常相似,不同之处在于,它不是在引入变量而是在引入类型。

Another way to see this: this is equivalent to breaking things apart into two separate statements: 另一种看待这种情况的方式:这相当于将事物分解为两个单独的语句:

typedef struct {
   ...
} A;

typedef A* B;

Here, the first one says " A now refers to this struct type, and B now refers to a pointer to an A ." 在这里,第一个表示“ A现在引用此struct类型,而B现在引用指向A的指针”。

I have seen this type of definition a lot in Microsoft code: 我在Microsoft代码中经常看到这种类型的定义:

typedef struct {
    int count;
    char buffer[128];
} BUFFER, *PBUFFER;

It allows code like this to be written: 它允许编写如下代码:

void read_buffer(PBUFFER pBuffer) {
    // Do something with pBuffer
}

int main(void) {
    BUFFER buffer;

    read_buffer(&buffer);
    return 0;
}

To directly answer your question: This kind of typedef allows a type and a pointer to a type to be defined at the same location in the code. 直接回答您的问题:这种typedef允许在代码中的同一位置定义一个类型和一个指向该类型的指针。

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

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