What does passing two aliases to `typedef struct` mean?

Viewed 199

What does *B in the following code mean? I understand this mixture between typedef and struct. However, this *B is strange.

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

I saw multiple questions asking about mixing typedef with struct but non of them talked about this double definition.

2 Answers

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. Here, this says

  • make an alias named A that represents the struct itself, and
  • make an alias named B that represents a pointer to the 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. 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.

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."

I have seen this type of definition a lot in Microsoft code:

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.

Related