From f126fd27a3d895c02e72fbfaa4d0dae583f9636f Mon Sep 17 00:00:00 2001 From: FreeArtMan Date: Mon, 8 Aug 2022 10:52:29 +0100 Subject: Add chapters on structures --- md/notes/undefined_c/titles.md | 61 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/md/notes/undefined_c/titles.md b/md/notes/undefined_c/titles.md index 2a47cc0..2c5bcd1 100644 --- a/md/notes/undefined_c/titles.md +++ b/md/notes/undefined_c/titles.md @@ -180,6 +180,67 @@ Yes there is possible to write as many expressions as needed. ### Structure + +Structure allows to combine types under one new type. Structure is convenient way how to combine set +of types and reuse them as one. + +```c +struct struct1 { + uint8_t a; + uint16_t b; + uint32_t c; + uint64_t d; +}; +``` + +Total intuitive size of structure would be +```c +int total_szie = sizeof(uint8_t) + sizeof(uint16_t) + sizeof(uint32_t) + sizeof(uint64_t); +int real_size = sizeof(struct1); +``` + +Types are placed inside structure to make fast access to them. Some instructions of CPU may require +to access aligned memory addresses to not have penalty on accessing types inside structure. + +To directly mess with alignment of types use attribute +```c +__attribute__ ((aligned (8))) +``` + + +Use attributes to pack structure and be not architecture dependent. + +```c +struct struct2 { + uint8_t a; + uint16_t b; + uint32_t c; + uint64_t d; +} __attribute__((packed)); +``` + +Now let check size of structure after it packed + +```c +int new_size = sizeof(struct2); +``` + +Also there is possible to add aligmnet to each time in structure +```c +struct struct3 { + uint8_t a __attribute__((aligned (8))); + uint16_t b __attribute__((aligned (8))); + uint32_t c __attribute__((aligned (8))); + uint64_t d __attribute__((aligned (8))); +} __attribute__((aligned (8))); +``` + +Now size of structure will be 32. + +All results on amd64, other arch may differ. + + + ### Recursion ### Macro ### Signed/Unsigned -- cgit v1.2.3