4 ms·
Because all pointers are the same size in C, and a pointer to a struct always points to the first member of the struct, you can do inheritance by having the "su
by mtlmtlmtlmtl 3y ago
Because all pointers are the same size in C, and a pointer to a struct always points to the first member of the struct, you can do inheritance by having the "superstruct" be the first member of the substruct:
struct foo {
...
};
struct bar {
struct foo super;
...
};
You can now safely pass a pointer to bar into a function that takes pointer to foo.
- jjgreen 3y agoall pointers are the same size in C Generally true, but not guaranteed by the standard: https://stackoverflow.com/questions/1241205/ https://stackoverflow.com/questions/1241205/
- rezonant 3y agoParticularly function pointers may have different sizes than what you'd expect. Thus it's best practice to always use sizeof() for the specific type of pointer you are interested in if you need to know it at runtime just as with any normal non-pointer type.
- isidor3 3y agoFrom that same post, though, referencing the C 11 standard > "All pointers to structure types shall have the same representation and alignment requirements as each other." And so the concern wouldn't apply to this pattern?
- deleted 3y ago[deleted]
- crabbone 3y agoTraditionally, pointers to functions were an exception. But I haven't red the new standards. I just assume pointers aren't all the same size, and don't try to rely on their size.
- mtlmtlmtlmtl 3y agoRight, my bad. It's really struct pointers that are guaranteed to be the same size.
- michaelcampbell 3y agoI've been out of the c/c++ game for a long time, but it's always interesting to see what the edge, or non-guaranteed, elements are going to be whenever anyone claims: > all|every|always ... in C.
- commonlisp94 3y agoIn modern times, this only applied to MSDOS
- jjgreen 3y agoNear, far and huge pointers; those were the days ...