Home > Net >  Struct access in C
Struct access in C

Time:12-15

This might seem a very stupid question but how is the member access operation in struct performed?

When you write struct_name.member_name how does the machine know which member to be accessed? Structs are stored in a contiguous block of memory with some padding(depends) and there is no sort of mapping of member identifiers to memory locations afaik. Unlike arrays, structs cant be accessed using base address offset and size (am I right?) so how does it happen ? Does the access take O(1) or not and what is the reason for it?

CodePudding user response:

I don't know why you assume there is no mapping between identifiers and memory locations? Access to members of structs/classes is just: address of instance (struct) offset of member. So yes, access to any member is constant time O(1)

You can see https://en.cppreference.com/w/c/types/offsetof :)

CodePudding user response:

The compiler knows where each member in the structure is, relative to the beginning of the structure. So, given struct_name.member_name, it adds the offset of member_name within the structure to the base address of the structure and accesses that address.

Does the access take O(1)

Yes.

  • Related