简体   繁体   中英

Pointer typecasting in c

I am writing an implementation of graphs in C language. I came across a situation where I am not able to figure out the reason for the way the compiler is behaving with a pointer typecast warning. Here are the structures;

#define MAXV 10 
typedef struct {
    int y;
    int weight;
    struct edgenode *next;
} edgenode;


typedef struct {
   edgenode *edge[MAXV+1];
   int degree[MAXV+1];
   // other info of graph
} graph;

// operation in some other function
p->next = g->edge[x];

I got a pointer typecast warning[enabled by default] when I do this kind of operation.

I was not able to remove this warning even after trying to typecast with every possible cast.
Finally I made a code change in the structure and suddenly the warning was gone. The structure code change was this:-

typedef struct edgenode {   // note that I have added structure name here
    // same as above definition
} edgenode;

// operation in some other function
p->next = g->edge[x];

Now the warning is gone and code runs without any warnings.

I do not understand why is this happening; can anybody help me with this problem?

The problem is here:

typedef struct {
    int y;
    int weight;
    struct edgenode *next;
} edgenode;

It is not clear what type struct edgenode *next; is referring to (it doesn't matter; somewhere, presumably, there's a struct edgenode defined), but it is not this structure because it has no tag. You need:

typedef struct edgenode
{
    int y;
    int weight;
    struct edgenode *next;
} edgenode;

Now the pointer refers to another structure of this same type. So, the fix you found was the correct fix for your problem.

Remember: a typedef is an alias (alternative name) for an existing type. You created a type name edgenode , but you had not defined the type struct edgenode . You don't have to fully define a structure type before you create pointers to it; this can be a good way of creating 'opaque types'.

The other way to define things is:

typedef struct edgenode edgenode;

struct edgenode
{
    int y;
    int weight;
    edgenode *next;
};

This says that the type name edgenode is an alias for a struct edgenode ; the structure definition then tells the compiler what a struct edgenode looks like.

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