#include<stdio.h>
int main()
{
struct test
{
char c;
int y;
float r;
double d;
} t1;
printf("%d\n",sizeof(t1));
return 0;
}
Output: 24 on my gcc 4.3.2 Ubuntu 12.04
Output: 20 on Ideone Link for Running Code
My Explanation: I think 24 is right. Correct me if i am wrong ?
Thus Size = 1(char) + 3(Padded in Char case) + 4(int) + 4(float) + 4(padded for Double) + 8(double) = 24
For Clarity:
Since Chunks are taken in 4 byte collection. so every address will be Multiple of 4. For double , Next address has to be 1012. but it is not multiple of 8. so pad it ! and start from 1016 My Question - Is 24 correct and my explanation correct or my explanation is wrong else please explain ?
Programs require data to be input. This data is used (processed) by the program, and data (or information ) is output as a result.
Example 1: C Output The code execution begins from the start of the main() function. The printf() is a library function to send formatted output to the screen. The function prints the string inside quotations.
Output of Program A program or other electronic device's output is any information it processes and sends out. Anything visible on the monitor screen, such as the words you write on your keyboard, is an example of the output.
Your explanation is correct in the sense that the specific compiler outputs a binary with a specific layout for that struct. If you have correctly predicted the outputs, then your prediction is obviously correct for your specific setup at this specific time.
But the struct's size is not, by any means, strictly defined in C. The only thing that's defined in this subject is the order of the struct members and the offset of the first member. The padding and, therefore, the total size of the struct is undefined and it's left as a decision for the compiler. Obviously, the main reason a compiler would pad the struct is higher performance through proper alignment of the members based on their individual types (as you correctly noted). But (and this is important here) the compiler chooses the most efficient padding depending on the target architecture. If an architecture has a 128-bit int, for instance, you can imagine how the size of your struct would be radically different.
So, if it comes to the defined aspects of the C language (or to any setup other than what you described) your prediction would be baseless. It would naturally match some setups, but only by accident.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With