offsetof related experiments
This commit is contained in:
parent
2ee6360820
commit
6c0848ab01
17
offsetTest/Makefile
Normal file
17
offsetTest/Makefile
Normal file
@ -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
|
||||
|
47
offsetTest/test.c
Normal file
47
offsetTest/test.c
Normal file
@ -0,0 +1,47 @@
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <stddef.h>
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user