0

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?

6
  • 3
    The compiler decides how the members are organised in the struct, in accordance with the C Standard's rules. So it knows what the offset of each member is. Whether the compiler uses an instruction that contains an offset from the base, or whether it is able to compute the actual address of the member, is an implementation detail. Commented Dec 15, 2021 at 10:34
  • 3
    Write a small program. Look at the generated assembly. Commented Dec 15, 2021 at 10:35
  • 2
    search packing. packing by one compiler in a specific setting is not guaranteed to be the same as in another... then learn about endian-ness, etc. when you pass a struct pointer to a function, and it accesses a member, what do you believe it does other than access memory at an offset appropriate to the member? Commented Dec 15, 2021 at 10:36
  • 4
    "structs cant be accessed using base address offset and size" - false. Commented Dec 15, 2021 at 10:38
  • 2
    In general, variables and identifiers do not exist in machine code. Everything there is just addresses. Commented Dec 15, 2021 at 11:47

2 Answers 2

3

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 :)

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

@EricPostpischil I was wrong
@EricPostpischil GAH! I cannot delete an accepted answer...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.