1

I was writing the code to check size of the int ,char and some struct.But its giving different result than manually calculated one.

#include<stdio.h>
struct person
{
    int roll;
    char name[10];

};  
void main()
{
    struct person p1;
    printf("\n The size of the integer on machine is \t :: %d \n ",sizeof(int));
    printf("\n The size of the char on machine is \t :: %d \n ",sizeof(char));

    printf("\n The size of structre is \t :: %d \n",sizeof(struct person)); 
    printf("\n The size of structre is \t :: %d \n",sizeof(p1));    


}

I think structure shall have size = 10 * 1 + 4 = 14. But the output is

 The size of the integer on machine is   :: 4 

 The size of the char on machine is      :: 1 

 The size of structre is     :: 16 
Jeremy West
  • 11,495
  • 1
  • 18
  • 25
alpha9eek
  • 1,439
  • 3
  • 11
  • 10

2 Answers2

1

See what wikipedia says!

To calculate the size of any object type, the compiler must take into account any address alignment that may be needed to meet efficiency or architectural constraints. Many computer architectures do not support multiple-byte access starting at any byte address that is not a multiple of the word size, and even when the architecture allows it, usually the processor can fetch a word-aligned object faster than it can fetch an object that straddles multiple words in memory.[4] Therefore, compilers usually align data structures to at least a word alignment boundary, and also align individual members to their respective alignment boundaries. In the following example, the structure student is likely to be aligned on a word boundary, which is also where the member grade begins, and the member age is likely to start at the next word address. The compiler accomplishes the latter by inserting unused "padding" bytes between members as needed to satisfy the alignment requirements. There may also be padding at the end of a structure to ensure proper alignment in case the structure is ever used as an element of an array. Thus, the aggregate size of a structure in C can be greater than the sum of the sizes of its individual members. For example, on many systems the following code will print 8:

struct student{
  char grade; /* char is 1 byte long */
  int age; /* int is 4 bytes long */
};

printf("%zu", sizeof (struct student));

You should try by altering the size of char array in your structure for better understanding

for example:

struct person
{
    int roll;
    char name[4];

};  

Gives answer as 8

struct person
{
    int roll;
    char name[7];

};

Gives answer as 12

Nullpointer
  • 1,086
  • 7
  • 20
0

First you need to change %d to %zu because sizeof returns size_t type.

sizeof(p1) is giving 16 bytes instead of 14 because padding 2 bytes are added to it.

struct person
{
    int roll;      // 4 bytes
    char name[10]; // 10 bytes. 2 bytes are needed for structure alignment 

};  
haccks
  • 104,019
  • 25
  • 176
  • 264