Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef struct pointer definition

I'm pretty new in C and having some problems with all the pointer stuff.

I wrote this code:

typedef struct edgeitem
{
    double          weight;
}EDGE_ITEM, *pEDGE_ITEM; //also declaration of a pointer

/************ edge that includes a pointer to the edge item, next and prev ******/
typedef struct edge
{
    pEDGE_ITEM  *edge_item;  
    pEDGE       *next;      //pointer to next edge
    pEDGE       *prev;      //pointer to prev edge
}EDGE, *pEDGE;

I get an error this way and just cant understand why.

I know that edgeitem and edge are tags and I can use struct edge *next but I declared the pointers so how come i can't use them?

Do i need to use * if I have a pointer?

pEDGE_ITEM *edge_item
//or
pEDGE_ITEM edge_item

I cant understand, it's a pointer so why do I add the *?

And the last question is: If I'm using the above, what's the difference between:

*EDGE  next
EDGE  *next

and last one : if I'm adding:

typedef struct edge_list
{
    EDGE        *head;
}EDGE_LIST;

is it the same as :

pEDGE      head;
like image 474
user1386966 Avatar asked May 26 '12 18:05

user1386966


1 Answers

You cannot use pEDGE within the definition of the struct. You shoud do something like:

typedef struct edge {
    pEDGE_ITEM          *edge_item;  
    struct edge         *next;      //pointer to next edge
    struct edge         *prev;      //pointer to prev edge
} EDGE, *pEDGE;

You must also note that edge_item is a double pointer. You also mention that in your question. So if you use pEDGE_ITEM and you just want to have a normal pointer you should not write pEDGE_ITEM *edge_item but just pEDGE_ITEM edge_item.

For clarifying, all the following declarations are equivalent:

struct edgeitem *edge_item;
EDGE_ITEM *edge_item;
pEDGE_ITEM edge_item;

But

pEDGE_ITEM *edge_item;

is equivalent to

struct edgeitem **edge_item;
EDGE_ITEM **edge_item;

About *EDGE next that is wrong syntax. The correct syntax would be EDGE* next or pEDGE next. So once struct edge is defined you can just use any of these two, but while defining the struct, you must do as I show at the beginning of my answer.

Yes, the following two definitions are equivalent:

typedef struct edge_list {
    EDGE        *head;
} EDGE_LIST;

typedef struct edge_list {
    pEDGE        head;
} EDGE_LIST;
like image 166
betabandido Avatar answered Sep 27 '22 20:09

betabandido