C stddef offsetof() Macro
Example
Find the position of each member in a struct:
struct Person {
char initial;
int age;
double height;
};
int main() {
printf("%zu\n", offsetof(struct Person, initial));
printf("%zu\n", offsetof(struct Person, age));
printf("%zu\n", offsetof(struct Person, height));
return 0;
}
Definition and Usage
The offsetof() macro returns how many bytes from the start of a struct a member begins.
The compiler can add padding (unused bytes) between the members, so a position is not always the sum of the sizes before it. In the example, initial uses 1 byte, but age starts at byte 4 on most systems, because 3 bytes of padding are added.
The offsetof() macro is defined in the <stddef.h> header file.
Syntax
size_t offsetof(type, member);
Parameter Values
| Parameter | Description |
|---|---|
| type | Required. A struct type, for example struct Person. |
| member | Required. The name of a member in the struct. |
Technical Details
| Returns: | A size_t value with the position of the member, in bytes from the start of the struct. |
|---|
Related Pages
Read more about padding in our C Struct Padding Tutorial.