I ran an experiment on cpp.sh (no special flags) where the word size seems to be 4 bytes. In my experiment, I initialized two elements of type Data
, a struct with just a single char, on the stack and printed out their addresses. I did the same with two variables of type char.
#include <iostream>
#include <bitset>
struct Data {
char c;
};
void PrintAddr(const void* ptr) {
std::cout << std::bitset<32>((unsigned int) ptr) << std::endl;
}
int main()
{
std::cout << "word size = " << sizeof(size_t) << std::endl;
std::cout << "sizeof = " << sizeof(Data) << std::endl;
std::cout << "alignof = " << alignof(Data) << std::endl;
std::cout << "Data addresses: " << std::endl;
Data a, b;
PrintAddr(&a);
PrintAddr(&b);
std::cout << "char addresses: " << std::endl;
char c, d;
PrintAddr(&c);
PrintAddr(&d);
}
Output:
word size = 4
sizeof = 1
alignof = 1
Data addresses:
00000000010100000101001011101000
00000000010100000101001011100000
char addresses:
00000000010100000101001011011111
00000000010100000101001011011110
It seems like padding is being added for variables a and b, of type Data, while there is none being added for type c and d. Why is this the case?
c
when asking a question about C++. These are two distinct languages.std::endl
does.’\n’
ends a line.char
and astruct
.