Explanation:sizeof(a) is the size of the whole array in bytes (24). sizeof(a[0]) is the size of one element (4). 24 / 4 = 6. This is the classic idiom for getting an array's length.
Question 3 — Out-of-bounds access
int a[3] = {10, 20, 30};
printf("%d\n", a[3]);
What happens?
0
30
Compile error
Undefined behavior (garbage value)
Explanation:a[3] is out of range (valid indices are a[0]..a[2]). C does not raise a compile error, but this is undefined behavior. Anything may happen, and it's a common source of security vulnerabilities.
Question 4 — Sum with a for loop
int a[4] = {2, 4, 6, 8};
int sum = 0;
for (int i = 0; i < 4; i++) {
sum += a[i];
}
printf("sum = %d\n", sum);
What does this print?
sum = 16
sum = 20
sum = 10
sum = 8
Explanation: 2+4+6+8 = 20. A standard pattern for summing all elements of an array with a for loop.