1 year ago
#160592
F.C. Akhi
What is happening struct padding or packing in 64 bit computer
Code 1
#include <stdio.h>
//structure var
struct var{
char a;
};
int main()
{
struct var r;
printf("%ld\n", sizeof(r));
return 0;
}
Output: 1
I know the concept of padding and packing. Padding happens when a 64-bit processor process 8byte data at a time.
So, if the concept of padding is applied in the above code then, 1------- = 8 bytes should be taken at a time for the process. And the size of struct var should show 8, not 1. That is (1-------) bytes. The First 1 represents 1 byte for char a
. And last 7 -------
are empty. Or here there is no padding happening but packing, something like that?
Code 2
#include <stdio.h>
struct var{
char a;
int b;
};
int main()
{
struct var r;
printf("%ld\n", sizeof(r));
return 0;
}
Output: 8
In the 2nd snippet of code, in the struct, there is 1 char and 1 int type variable has been declared. That is (1 1111 ---) bytes. The First 1 represents 1 byte for char a
and 2nd chunk of 4 1's represents 4 bytes for int b
. And last 3 ---
are empty.
Code 3
#include <stdio.h>
struct var{
char a;
int c;
int b;
};
int main()
{
struct var r;
printf("%ld\n", sizeof(r));
return 0;
}
Output: 12
In snippet code 3, we get 12 bytes as output. I am little bit confused here. How it is happening. In my calculation it should be 16 bytes. In first cycle processor will take 8 bytes (1 1111 ---) and in second cycle processor will take next 8 bytes (1111 ----). But, if for some reason it is not taking 8 bytes at a time, though it suppose to be because I am running 64-bit computer, then it is taking 4 bytes at a time. (1---), (1111) and (1111) bytes. That means to run this code it is using 3 cycles in total.
And if it is taking 4 bytes at a time for 64-bit computer, Why it is happening like that? In such case calculation for padding I did in 1st and 2nd code snippet will also be wrong.
c
struct
padding
packing
cpu-cycles
0 Answers
Your Answer