Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are structs actually implemented in the C programming language? [duplicate]

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.

like image 382
the_endian Avatar asked Aug 29 '17 06:08

the_endian


People also ask

How does C Store structs in memory?

In C#, struct 's memory is laid out by the compiler by default. The compiler can re-order data fields or pad additional bits between fields implicitly. So, I had to specify some special attribute to override this behavior for exact layout. AFAIK, C does not reorder or align memory layout of a struct by default.

Can we copy struct in C?

In C/C++, we can assign a struct (or class in C++ only) variable to another variable of same type. When we assign a struct variable to another, all members of the variable are copied to the other struct variable.

Can you copy a struct?

A struct variable in Golang can be copied to another variable easily using the assignment statement(=). Any changes made to the second struct will not be reflected back to the first struct.

Can you set structs equal to each other?

Yes if the structure is of the same type. Think it as a memory copy. Keep in mind that there's no deep copy, pointed to memory isn't copied.


1 Answers

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

like image 187
Vagish Avatar answered Sep 20 '22 14:09

Vagish