简体   繁体   中英

C typecasting for structure pointers

Confused in some example with realization of trivial intrusive container in C. I have structures:

struct List {
    struct Link* first;
    struct Link* last;
};

And Link for become the nodes of list:

struct Link {
    struct Link* pre;
    struct Link* suc;
}; 

Some pseudo Node for storing specified values in List:

struct Name {
    struct Link lnk;
    char* n;
};

Function for pushing values in List:

void push_back(struct List* lst, struct Link* p) {
    assert(lst);
    {
        struct Link* last = lst->last;
        if (last) {
            p->pre = last;          
            last->suc = p;                                      
        }
        else {
            lst->first = p;
            p->pre = 0;
        }
        lst->last = p;
        p->suc = 0;
    }
}

And usage of List:

int main() {

    int count = 0;
    struct List names;
    struct Link* curr;
    init(&names);

    push_back(&names, (struct Link*)make_name("Norah"));
    push_back(&names, (struct Link*)make_name("Annemarie"));
    push_back(&names, (struct Link*)make_name("Kris"));

    curr = names.first;
    for (; curr != 0; curr = curr->suc) {
        count++;
        printf("element %d: %s\n", count, ((struct Name*)curr)->n);
    }
    return 0;
}

Question is, how typecast is working in this example? when sizeof(Link)==8 and sizeof(Name)==12 The pointer curr pointing to allocated memory for type Name , this structure not have suc and pre members,just lnk object of type Name (not pointer), and in code no any primary access for this member.

It is relying on the fact that struct Link is the first field of the struct Name . You can pretend the 12 bytes pointed to by a struct Name* is actually an 8 byte struct Link , and disregard the remaining 4 bytes. See the following questions:

Thanks guys! Im lost from mind that struct Link have two first members which each one 4 bytes. When struct Name is come to push_back() via argument, the function is operate with him like a struct Link .Cuz struct Name have 8 byte member in a head, functions just placing data about suc and pre members in this 8 bytes. I can replace lnk member from Name to any other with data with size 8 bytes.

Have i nice day!

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