Last active
April 15, 2025 05:03
-
-
Save Pikachuxxxx/307155dde57da6fcacf76e7c59ce91ea to your computer and use it in GitHub Desktop.
A stupid trick to calculate the nu of entries of a array dynamically
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
#include <stdio.h> | |
#include <stdint.h> | |
#include <stddef.h> | |
#include <assert.h> | |
#define TEST_STRUCT_ENTRIES(struct_type, start_member, end_member, expected_count) \ | |
do { \ | |
size_t start_offset = offsetof(struct_type, start_member); \ | |
size_t end_offset = offsetof(struct_type, end_member); \ | |
size_t num_elements = (end_offset - start_offset) / sizeof(uint32_t); \ | |
printf("Testing %s:\n", #struct_type); \ | |
printf(" Size of struct: %zu bytes\n", sizeof(struct_type)); \ | |
printf(" Offset of %s: %zu bytes\n", #start_member, start_offset); \ | |
printf(" Offset of %s: %zu bytes\n", #end_member, end_offset); \ | |
printf(" Calculated number of uint32_t elements: %zu\n", num_elements); \ | |
assert(num_elements == expected_count); \ | |
assert(num_elements * sizeof(uint32_t) == sizeof(struct_type)); \ | |
printf(" Test passed.\n\n"); \ | |
} while (0) | |
typedef struct { | |
uint32_t a; | |
uint32_t b; | |
uint32_t c; | |
uint32_t _end_marker[]; | |
} Struct1; | |
typedef struct { | |
uint32_t x; | |
uint32_t y; | |
uint32_t z; | |
uint32_t w; | |
uint32_t _end_marker[]; | |
} Struct2; | |
typedef struct { | |
uint32_t m; | |
uint32_t n; | |
uint32_t _end_marker[]; | |
} Struct3; | |
typedef struct { | |
uint32_t p; | |
uint32_t q; | |
uint32_t r; | |
uint32_t s; | |
uint32_t t; | |
uint32_t _end_marker[]; | |
} Struct4; | |
typedef struct { | |
uint32_t u; | |
uint32_t v; | |
uint32_t _end_marker[]; | |
} Struct5; | |
int main() { | |
TEST_STRUCT_ENTRIES(Struct1, a, _end_marker, 3); | |
TEST_STRUCT_ENTRIES(Struct2, x, _end_marker, 4); | |
TEST_STRUCT_ENTRIES(Struct3, m, _end_marker, 2); | |
TEST_STRUCT_ENTRIES(Struct4, p, _end_marker, 5); | |
TEST_STRUCT_ENTRIES(Struct5, u, _end_marker, 2); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment