Size of struct that contains two pointers

放肆的年华 提交于 2019-12-01 06:12:21

The size of the struct is given by:

size_t size = sizeof(struct list_element);

The fact that you have two members that are pointers to the struct just means you are adding the size of a pointer, twice. On a 32 bit build, sizeof would resolve to an additional 4 bytes per pointer, on a 64 bit build, it would result in an additional 8 bytes per pointer.

Another thing to be aware of is that the size of your struct is likely not simply the sum of the sizeof's of the individual members, as storage in a struct is often padded for alignment purposes. So, between your short, and the next member, the padding will result in additional size.

The reason I used the word likely is that if a pragma pack directive was used in your source, the packing alignment could be changed, resulting in a different value for sizeof.

Two good discussions on struct alignment padding: A general discussion here, and How to reduce memory footprint here. The second link is particularly interesting as it deals with structure alignment, padding and bit fields, and how each can affect memory usage.

Although your teacher asked to ignore data alignment, the size of that struct is 10 bytes assuming short being 2 bytes.. but actually the short size is not fixed, but at least 2 bytes!

Give a look here. Did you correctly reported the teacher question?

Shravan40

This will return the size of the struct:

sizeof(struct list_element);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!