How to get the offset in bytes of a structure variables in C

2 Answers

0 votes
#include <stdio.h>
#include <stddef.h>

struct Address {
	char name[16];
	char street[32];
	int entry;
};

int main() {
	printf("name offset = %zd bytes from start of struct \n", offsetof(struct Address, name)); // 0

	printf("street offset = %zd bytes from start of struct \n", offsetof(struct Address, street)); // 0 + 16 = 16

	printf("phone offset = %zd bytes from start of struct \n", offsetof(struct Address, entry)); // 16 + 32 = 48

	return 0;
}


/*
run:

name offset = 0 bytes from start of struct
street offset = 16 bytes from start of struct
phone offset = 48 bytes from start of struct

*/

 



answered Feb 5, 2023 by avibootz
0 votes
#include <stdio.h>

struct Address {
	char name[16];
	char street[32];
	int entry;
};

int main() {
	printf("name offset = %zd bytes \n", ((size_t) &((struct Address*)0)->name)); // 0

	printf("street offset = %zd bytes \n", ((size_t) &((struct Address*)0)->street)); // 0 + 16 = 16

	printf("phone offset = %zd bytes \n", ((size_t) &((struct Address*)0)->entry)); // 16 + 32 = 48

	return 0;
}


/*
run:

name offset = 0 bytes
street offset = 16 bytes
phone offset = 48 bytes

*/

 



answered Feb 5, 2023 by avibootz
edited Feb 15, 2023 by avibootz

Related questions

1 answer 122 views
2 answers 174 views
1 answer 277 views
1 answer 204 views
204 views asked Nov 27, 2021 by avibootz
1 answer 103 views
103 views asked Jun 7, 2024 by avibootz
...