8

Structs are a composite data structure in the C programming language; they consist of primitives such as ints and pointers all placed in memory in an adjacent fashion, such as an array.

My question is, what are structs themselves made out of? Are they a type of array? For example, a hash table can be implemented as an array of linked-lists. In a similar way, what is a struct implemented as? If need be, please explain at the x86 assembly level. Thank you.

8
  • 1
    0s and 1s... this is a bit too broad as it is.
    – cs95
    Commented Aug 29, 2017 at 6:10
  • Not like an array, as far as I know. An array is contiguous, but structs may contain padding. Commented Aug 29, 2017 at 6:10
  • 1
    They aren't implemented "in the language itself". A C implementation uses a structure definition as a guide to access a piece of memory (in an implementation defined manner). After translation, any notion of human readable "structures" is gone. Commented Aug 29, 2017 at 6:12
  • 1
    They are not metadata, they are just data. You can look at it just as an abstraction, the same way arrays are. You only say something is an array if it makes sense for it to be, because of the operations performed on it, the access that is made. But you could very well just say they are different variables. In the assembly level there are in fact just variables.
    – savram
    Commented Aug 29, 2017 at 6:24
  • 1
    Wrong duplicate again. C and C++ are different languages and therefore the object layout has different rules altogether Commented Aug 29, 2017 at 9:25

1 Answer 1

3

At assembly level Structure boils down to a address accessed by offset corresponding to structure member.

Depending on the alignment rule and storage class memory is allocated for instance of structure.

Example:

struct A
{
  int a,
  char b
}a1;

In above case if you write a1.b = 5 its assembly equivalent would be something:

MOV 5 TO ADDRESS OF a1 + 4 //assuming integer size is 4

1
  • 2
    Good explanation. The next level of complication is that compilers are allowed to optimize away struct variables, same as they can for other objects. The struct doesn't have to have an address; the member values could just be held in registers even if it's not optimized away. (e.g. after inlining a function that returns a struct by value). Commented Aug 29, 2017 at 7:04

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.