Last active
November 9, 2016 21:02
-
-
Save janvanmansum/5fafd4b27d7d0b2d1b9b49680db71f80 to your computer and use it in GitHub Desktop.
The gist of C structs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // s1 is a structured field with two int fields: a and b | |
| struct { | |
| int a, b; | |
| } s1, *ps1; | |
| // s2 is the same type of structured field as s1, only that "type" has no name. | |
| struct { | |
| int a, b; | |
| } s2, *ps2; | |
| // s2a has the same "structure" as s1, *ps1, s2 and *ps2, but the fields have different names. | |
| struct { | |
| int x, y; | |
| } s2a; | |
| // WARNING: "Declaration doesn't declare anything". We define a structure, but no | |
| // variables that use it, nor a way to refer to it. | |
| struct { | |
| int c, d; | |
| }; | |
| // Give the structure a tag ... | |
| struct cd { | |
| int c, d; | |
| }; | |
| // s3 now has the structure defined by the previous declaration | |
| struct cd s3; | |
| // Alternative: define a name for a structure type. | |
| typedef struct { | |
| int e, f; | |
| } ef_t; | |
| // Now we don't need the struct keyword | |
| ef_t s4; | |
| // Do both: a struct tag and a typedef ... a bit confusing, but legal | |
| typedef struct gh { | |
| int g, h; | |
| } gh_t; | |
| gh_t s5; | |
| struct gh s6; | |
| // gh s7; illegal | |
| // struct gh_t s8; illegal | |
| // Ways in which we can and cannot use above variables. | |
| int main(void) { | |
| s1.a = 1; | |
| s1.b = 2; | |
| s2.a = 1; | |
| s2.b = 2; | |
| ps1 = &s1; | |
| ps1->a = 0; | |
| // ps2 = &s1; // Getting a compiler warning, so does not seem to be legal, even though the two structs have the same fields. | |
| // ps2 = &s2a; // The above doesn't work, so this wouldn't work then, either. | |
| s3.c = 3; | |
| s3.d = 4; | |
| s4.e = 5; | |
| s4.f = 6; | |
| s5.g = 7; | |
| s5.h = 8; | |
| s6.g = 7; | |
| s6.h = 8; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment