简体   繁体   中英

What does it mean to typedef a struct as an array?

The graph adjacency list code in my book is given by:

typedef struct vertexNode //vertexNode in an AdjacencyList
{
    VertexType data; 
    EdgeNodeType *firstEdgeNode;

} VertexNode, AdjList[MAXVEX];

AdjList adjList; # adjList is a MAXVEX-size array 

I was confused by the last line in the typedef: typedef struct{...} AdjList[MAXVEX] .

The forms I can understand are:

typedef struct{
...
} VertexNode,

VertexNode AdjList[MAXVEX]; # AdjList is a MAXVEX-size array 

or

struct{
...
} AdjList[MAXVEX]; # AdjList is a MAXVEX-size array 

Grammatically speaking, typedef is actually a storage class, like static or extern , and type alias declarations are read like variable declarations. Eg

int x;

declares x to be a variable of type int , while

typedef int x;

declares x to be a type alias meaning int .

Similarly,

struct vertexNode {
    ...
} VertexNode;

would declare VertexNode to be a struct vertexNode variable, but adding typedef makes it an alias for struct vertexNode . Note that struct vertexNode { ... } (the whole thing) is a type, just like int . It first defines struct vertexNode , and then refers to it.

Additionally, array declarations may appear to behave strangely when you use commas:

int x, y[5];

declares x to be an int , while declaring y to be an array of 5 int s. (Functions and pointers are also like this.) There are other questions on this site about it.

Putting everything together, your question looks like this if you take away the typedef :

struct vertexNode
{
    VertexType data; 
    EdgeNodeType *firstEdgeNode;
} VertexNode, AdjList[MAXVEX];

This would declare the type struct vertexNode , the variable VertexNode of type struct vertexNode , and the array AdjList of MAXVEX struct vertexNode s. Adding the typedef means that VertexNode becomes an alias for struct vertexNode and that AdjList becomes an alias for an array of MAXVEX struct vertexNode s. Personally, I wouldn't recommend writing it like this, but I guess it's concise.

This is a sample code.

#include <stdio.h>

typedef char STR[1024];

int main() {
    STR a = "1234";       // == char a[1024]
    printf( "%s\n", a );

    return 0;
}

I wrote a example with data type char . You can replace it with any class or struct..

so.. Your code..

AdjList a is same with VertexNode a[MAXVEX]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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