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.