-
Notifications
You must be signed in to change notification settings - Fork 0
/
struct_casting.c
42 lines (33 loc) · 891 Bytes
/
struct_casting.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
* So this is really cool and I should've figured it out way sooner. It makes so
* much sense!
*
* you can move around a pointer to a "public" struct that's a member to another
* private one, and to access the private one you just cast that pointer
*
* This could be a primitive way to think of "inheritance" or subtyping of sorts
* (please don't bring OOP mindset to C programs though)
*/
#include <stdio.h>
struct pub_s {
int a;
char b[128];
};
struct priv_s {
struct pub_s pub; /* NOTE: has to be at the beginning to share the same pointer! */
char secret[128];
};
int main(void) {
struct priv_s private = {
.pub = {
.a = 9,
.b = "thousand!"
},
.secret = "cool secret!"
};
struct pub_s *public = &private.pub;
printf("it's over %d %s\n", public->a, public->b);
printf("also:\n");
printf("%s\n", ((struct priv_s*) public)->secret);
return 0;
}