From 6c0848ab01960292987b4876c7b3bb3391903e07 Mon Sep 17 00:00:00 2001 From: Wolfgang Hottgenroth Date: Sat, 12 Dec 2020 20:24:58 +0100 Subject: [PATCH] offsetof related experiments --- offsetTest/Makefile | 17 ++++++++++++++++ offsetTest/test.c | 47 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 offsetTest/Makefile create mode 100644 offsetTest/test.c diff --git a/offsetTest/Makefile b/offsetTest/Makefile new file mode 100644 index 0000000..c1a51ca --- /dev/null +++ b/offsetTest/Makefile @@ -0,0 +1,17 @@ +CFLAGS= + +test: test.o + gcc -o $@ $^ + +test.o: test.c + gcc -c -o $@ $(CFLAGS) $^ + + +.PHONY: run +run: test + ./test + +.PHONY: clean +clean: + rm -f *.o test + diff --git a/offsetTest/test.c b/offsetTest/test.c new file mode 100644 index 0000000..4e6ce27 --- /dev/null +++ b/offsetTest/test.c @@ -0,0 +1,47 @@ +#include +#include +#include +#include +#include + +typedef struct { + uint8_t id; + char a[16]; + uint8_t length; +} t_testObj; + +t_testObj testObj = { .id = 0, .a = "test123", .length = 25 }; + +void printTestObj(t_testObj *testObj) { + printf("testObj: id=%d, a=%s, length=%d\n", testObj->id, testObj->a, testObj->length); +} + +int main() { + printf("id: %ld\n", offsetof(t_testObj, id)); + printf("a: %ld\n", offsetof(t_testObj, a)); + printf("length: %ld\n", offsetof(t_testObj, length)); + + printTestObj(&testObj); + + strcpy(testObj.a, "demo234"); + printTestObj(&testObj); + + uint8_t *a1 = (uint8_t*)&testObj; + printf("a1: %p\n", a1); + + uint8_t *a2 = ((uint8_t*)&testObj) + offsetof(t_testObj, length); + printf("a2: %p\n", a2); + + *a2 = 35; + printTestObj(&testObj); + + uint8_t *a3 = ((uint8_t*)&testObj) + offsetof(t_testObj, a); + printf("a3: %p\n", a3); + + strcpy((char*)a3, "Wolfgang"); + printTestObj(&testObj); +} + + + +