What is the output of this C code snippet?
#include <stdio.h> int main() { int arr[10]; int *ptr = arr; printf("%zu %zu\n", sizeof(arr), sizeof(ptr)); return 0; }
Remember that sizeof on an array gives total bytes, but on a pointer gives pointer size.
The array arr has 10 integers. Each int is 4 bytes on a 32-bit system or 4 bytes on many embedded systems, so total 40 bytes. The pointer ptr size depends on architecture; on a 64-bit system it is 8 bytes. So output is "40 8".
Given this struct, what is the total size in bytes on a system where int is 4 bytes and alignment is on 4-byte boundaries?
struct S {
char a;
int b;
char c;
};Think about padding added to align int b and the struct size.
The struct has char a (1 byte), then 3 bytes padding to align int b (4 bytes), then char c (1 byte), then 3 bytes padding to make total size multiple of 4. Total size is 12 bytes.
What error causes the wrong total size calculation in this code?
struct Data {
char flag;
double value;
};
int total_size() {
return sizeof(char) + sizeof(double);
}Think about how structs are aligned in memory.
Adding sizes of members ignores padding bytes added by compiler for alignment. The double usually requires 8-byte alignment, so padding is added after flag. Summing sizes misses this padding, underestimating total size.
Which option correctly allocates memory for an array of 5 integers?
Consider what sizeof(arr) and sizeof(*arr) mean.
sizeof(*arr) gives size of one integer (the type pointed to). sizeof(arr) gives size of pointer, which is not correct for allocation. Options A and B are correct but C is preferred for safety and maintainability.
Given these structs, what is the total size of struct Container on a system where int is 4 bytes, char is 1 byte, and alignment is on 4-byte boundaries?
struct Inner {
char x;
int y;
};
struct Container {
struct Inner a;
char b;
};Calculate size of Inner first including padding, then add b with padding.
Inner has char x (1 byte), 3 bytes padding, then int y (4 bytes), total 8 bytes. Container has Inner a (8 bytes), then char b (1 byte), plus 3 bytes padding to align total size to 4 bytes. Total size is 12 bytes.