Friday, 22 March 2013

C/C++ Puzzles: PART - 28

Sizeof Structure Variables

  Consider the code given below. What is the Output? 

struct outer_str 

    struct nest_str1 
    { 
         int mem1; 
    }; 
    struct nest_str2 
    { 
         int mem2; 
    }nest_var2; 
}outer_var; 

int main( ) 
{
      printf("\n\nThe size of structure variable outer_var is %d\n\n",sizeof(outer_var)); 
      return 0;
}
Click here to download the C Program.
The expected Output is 8 bytes. But the actual Output is 4 bytes. Why?

Figure Below Shows the Output

  The inner structure nest_str1 does not have any structure variable associated with it. So there is no memory allocated for this structure. Thus the total memory size of the outer structure variable is just 4 bytes. The program given below will show a size of 8 bytes.

struct outer_str 

    struct nest_str1 
    { 
         int mem1; 
    }nest_var1; 
    struct nest_str2 
    { 
         int mem2; 
    }nest_var2; 
}outer_var; 

int main( ) 
{
      printf("\n\nThe size of structure variable outer_var is %d\n\n",sizeof(outer_var)); 
      return 0;
}

No comments:

Post a Comment