开发者

Return from incompatible pointer type C

I'm still trying to get to grips with point开发者_JS百科ers,structures and malloc in C. I'm trying to impliment a hash table using linked lists. I'm getting a return from incompatible pointer type error when I try to compile:

struct Mlist_head{
    struct Mlist_node *head;
    struct Mlist_node *tail;
};

struct MList {
    int size;
    struct Mlist_head hashtable[HASHSIZE];
};

MList *ml_create(void){ 

    struct MList *m;
    struct Mlist_head *h;
    int i;

    if ((m = (struct MList *)malloc(sizeof(struct MList))) != NULL){
        if ((h = (struct Mlist_head *)malloc(sizeof(struct Mlist_head))) != NULL) { 
            for (i = 0; i < HASHSIZE; i++) {
                h = &(m->hashtable[i]);
                h->head = NULL;
                h->tail = NULL;
            }
            printf("worked");
            return m;
        }
    }
}

I'm sure there could be other errors in here (possibly semantic) but one thing at a time :)

Thanks for any help


MList *ml_create(void){ 

Should be

struct MList *ml_create(void){ 


In C, a struct declaration doesn't automatically introduce a new type. You need to use the struct keyword with the name you gave the structure (which is technically called the struct's tag):

struct MList *ml_create(void);

You can work around this by defining a new type name, using the typedef keyword:

typedef struct Mlist_head MList;

Now you can do:

MList ml_create(void);

Also:

  • In C, don't cast the return value of malloc().
  • Consider using sizeof *h rather than sizeof (struct Mlist_head); it's shorter and less error-prone.

For these last two points, compare your code:

if ((m = (struct MList *)malloc(sizeof(struct MList))) != NULL){

with this, which is how I would write it:

if ((m = malloc(sizeof *m)) != NULL) {

To me, the latter is much much easier to read since it has less noise, and it's also safer since it doesn't repeat the type name. If the type of the m pointer later changes, my verrsion is still 100% correct.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜