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

1 Answer

0 votes
#include <iostream>

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

int main()
{
    const int offsetof_name = offsetof(Address, name); 
    const int offsetof_street = offsetof(Address, street); 
    const int offsetof_entry = offsetof(Address, entry); 
    
    std::cout << "offset of name: " << offsetof_name << " bytes from start of struct\n"; // 0
    std::cout << "offset of street: " << offsetof_street << " bytes from start of struct\n"; // 0 + 16 = 16
    std::cout << "offset of entry: " << offsetof_entry << " bytes from start of struct\n"; // 16 + 32 = 48
}



/*

run:

offset of name: 0 bytes from start of struct
offset of street: 16 bytes from start of struct
offset of entry: 48 bytes from start of struct

*/

 



answered Feb 5, 2023 by avibootz

Related questions

2 answers 162 views
2 answers 174 views
2 answers 148 views
1 answer 123 views
1 answer 119 views
...