gpuguy
gpuguy

Reputation: 4585

Array of structure Layout in Memory

 int a[2];

This in memory actually looks like:

 //Assuming int is 2 bytes 

 add=2000, a[0]=124    

 add=2002, a[1]=534 

How does this actually look like in memory

 struct l {

 struct l    * n;

 long int pad[7];

 };          

 struct l container;

I am unable to visualize. Please help!

BTW this is taken from section 3.3.2 of What Every Programmer Should Know About Memory

Upvotes: 2

Views: 204

Answers (3)

Anthony Choi
Anthony Choi

Reputation: 106

this just means every time you allocate memory for struct l, you will need 4 byte (pointer) + 4 byte (let's say long int is 4 byte) * 7.

so using your system, it should be: add=2000 *n add=2004 pad[0] add=2008 pad[1] ...

Upvotes: 1

Dave Rager
Dave Rager

Reputation: 8150

Assuming a pointer in your architecture is 4 bytes and a long int in your architecture is 4 bytes:

struct l {
   struct l    * n;
   long int pad[7];
};

struct l someName;

layout will look like:

add=2000, someName.n
add=2004, someName.pad[0]
add=2008, someName.pad[1]
...
add=2028, someName.pad[6]

Upvotes: 2

Dima Chubarov
Dima Chubarov

Reputation: 17169

The layout of struct l would be as follows. As the book says it will occupy 32 bytes.

   addr   ref
   -----------------
   2000:  n
   2004:  pad[0]
   2008:  pad[1]
     ...
   2028:  pad[6]

On a 32-bit system struct l*, a pointer to a structure would occupy 4 bytes. A variable of type long int would occupy the same amount of memory.

Upvotes: 4

Related Questions