Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 669
user10927531 Avatar asked Nov 25 '19 01:11

user10927531


2 Answers

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

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 ints. (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 vertexNodes. Adding the typedef means that VertexNode becomes an alias for struct vertexNode and that AdjList becomes an alias for an array of MAXVEX struct vertexNodes. Personally, I wouldn't recommend writing it like this, but I guess it's concise.

like image 170
HTNW Avatar answered Oct 24 '22 13:10

HTNW


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]

like image 36
Peter Lee Avatar answered Oct 24 '22 12:10

Peter Lee