Consider the following C code that prints the size of different data types using sizeof. What will be the output?
#include <stdio.h> int main() { printf("%zu %zu %zu\n", sizeof(char), sizeof(int), sizeof(double)); return 0; }
Remember that char is usually 1 byte, int is commonly 4 bytes on modern systems, and double is often 8 bytes.
The sizeof operator returns the size in bytes of the given type. On most modern systems, char is 1 byte, int is 4 bytes, and double is 8 bytes.
Given the following code, what will be the output on a typical 64-bit system?
#include <stdio.h> int main() { int *p; printf("%zu\n", sizeof(p)); return 0; }
Think about the size of pointers on 64-bit architectures.
On 64-bit systems, pointers typically occupy 8 bytes because they need to store 64-bit addresses.
Consider this C code that prints the size of a struct with different data types. What is the output?
#include <stdio.h>
struct Data {
char c;
int i;
double d;
};
int main() {
printf("%zu\n", sizeof(struct Data));
return 0;
}Remember that structs may have padding to align data properly in memory.
The struct contains a char (1 byte), followed by 3 bytes padding, an int (4 bytes), and a double (8 bytes). Due to padding for alignment, the total size is 24 bytes on typical systems.
What will this program print when it runs?
#include <stdio.h>
union U {
char c;
int i;
double d;
};
int main() {
printf("%zu\n", sizeof(union U));
return 0;
}Unions allocate memory equal to the size of their largest member, possibly with padding.
The largest member is double which is 8 bytes. The union size is 8 bytes on typical systems.
Given the following struct with bit-fields, how many bytes does it occupy on a typical 64-bit system?
struct BitField {
unsigned int a : 3;
unsigned int b : 5;
unsigned int c : 6;
unsigned int d : 18;
};Bit-fields are packed into the smallest number of bytes that can hold all bits, aligned to the base type size.
The total bits are 3 + 5 + 6 + 18 = 32 bits, which fits exactly into 4 bytes (size of unsigned int). So the struct occupies 4 bytes.