Skip to content

Instantly share code, notes, and snippets.

@Ben1980
Last active September 14, 2020 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ben1980/1782ea2cd52c0732119d07bc1f6fd97f to your computer and use it in GitHub Desktop.
Save Ben1980/1782ea2cd52c0732119d07bc1f6fd97f to your computer and use it in GitHub Desktop.
#include <iostream>
void printTypeSize() {
std::cout << "Size of char = " << sizeof(char) << " byte" << std:: endl;
std::cout << "Size of short = " << sizeof(short) << " byte" << std:: endl;
std::cout << "Size of int = " << sizeof(int) << " byte" << std:: endl;
std::cout << "Size of long = " << sizeof(long) << " byte" << std:: endl;
}
struct S1 {
char a; // 1
int b; // 4
char c; // 1
short d; // 2
};
void printS1() {
std::cout << "Size of S1 = 1 + 4 + 1 + 2 = "
<< sizeof(char) + sizeof(int) + sizeof(char) + sizeof(short) << " byte, real size is "
<< sizeof(S1) << " byte" << std:: endl;
}
void printS1MemoryLayout() {
S1 s;
std::cout << "Address a: " << (void*)&s.a << std::endl;
std::cout << "Address b: " << (void*)&s.b << std::endl;
std::cout << "Address c: " << (void*)&s.c << std::endl;
std::cout << "Address d: " << (void*)&s.d << std::endl;
}
struct S2 {
char a; // 1
char c; // 1
short d; // 2
int b; // 4
};
void printS2() {
std::cout << "Size of S2 = 1 + 1 + 2 + 4 = "
<< sizeof(char) + sizeof(int) + sizeof(char) + sizeof(short) << " byte, real size is "
<< sizeof(S2) << " byte" << std:: endl;
}
void printS2MemoryLayout() {
S2 s;
std::cout << "Address a: " << (void*)&s.a << std::endl;
std::cout << "Address c: " << (void*)&s.c << std::endl;
std::cout << "Address d: " << (void*)&s.d << std::endl;
std::cout << "Address b: " << (void*)&s.b << std::endl;
}
struct S3 {
char a;
int b;
};
void printS3() {
std::cout << "Size of S3 = 1 + 4 = "
<< sizeof(char) + sizeof(int) << " byte, real size is "
<< sizeof(S3) << " byte" << std:: endl;
}
void printS3MemoryLayout() {
S3 s;
std::cout << "Address a: " << (void*)&s.a << std::endl;
std::cout << "Address b: " << (void*)&s.b << std::endl;
}
int main() {
printTypeSize();
printS1();
printS1MemoryLayout();
printS2();
printS2MemoryLayout();
printS3();
printS3MemoryLayout();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment