By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,553 Members | 866 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,553 IT Pros & Developers. It's quick & easy.

Determine the size of following structure

P: 1
Expand|Select|Wrap|Line Numbers
  1. Struct student
  2. { int rno ;
  3.    char name[20] ;
  4.    int n1, n2, total ;
  5. }
1 Week Ago #1
Share this Question
Share on Google+
2 Replies

Banfa
Expert Mod 5K+
P: 8,996
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.
1 Week Ago #2

dev7060
Expert 100+
P: 336
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.
1 Week Ago #3

Post your reply

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