469,647 Members | 1,800 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,647 developers. It's quick & easy.

Determine the size of following structure

Expand|Select|Wrap|Line Numbers
  1. Struct student
  2. { int rno ;
  3.    char name[20] ;
  4.    int n1, n2, total ;
  5. }
Nov 18 '20 #1
2 1849
Banfa
9,064 Expert Mod 8TB
That rather depends on the platform and the packing rules in play which can be changed on some compilers.

Have you tried using the sizeof operator, it would give you an answer although it will be platform specific.
Nov 18 '20 #2
dev7060
518 Expert 512MB
Determine the size of following structure
Total size = Size of the data members + Padding size

About padding:
Padding is implementation-defined. Added between the members and/or at the end to arrange memory and avoid alignment issues. Why padding? Because the processor can read one word at a time (word size = 4 bytes in 32-bit system and 8 in 64-bit system).
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. struct student {
  4.   int rno;
  5.   char name[20];
  6.   int n1, n2, total;
  7. } obj;
  8. int main() {
  9.   printf("Padding = %d", sizeof(obj)-(4 * sizeof(int) + 20 * sizeof(char)));
  10.   return 0;
  11. }
O/P: Padding = 0

Everything is aligned (multiples of 4).

Changing to introduce padding:
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. struct student {
  4.   int rno;
  5.   char name[19];
  6.   int n1, n2, total;
  7. } obj;
  8. int main() {
  9.   printf("Padding = %d\n", sizeof(obj)-(4 * sizeof(int) + 19 * sizeof(char)));
  10.   printf("%u\n", &obj.rno);
  11.   printf("%u\n", &obj.name);
  12.   printf("%u\n", &obj.n1);
  13.   printf("%u\n", &obj.n2);
  14.   printf("%u\n", &obj.total);
  15.   return 0;
  16. }
  17.  
O/P:
Padding = 1
3281444928
3281444932
3281444952
3281444956
3281444960

The padding of 1 empty byte is added before n1. The order of the data members could change the padding and hence the structure size.
Nov 20 '20 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

6 posts views Thread by MSReddy | last post: by
2 posts views Thread by mykidisgollum | last post: by
3 posts views Thread by John Williams | last post: by
4 posts views Thread by Anonymous | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.