Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,944 questions

51,885 answers

573 users

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 101 views
2 answers 124 views
1 answer 252 views
1 answer 152 views
152 views asked Nov 27, 2021 by avibootz
1 answer 77 views
77 views asked Jun 7, 2024 by avibootz
...