Difficulty: Medium
Correct Answer: By dividing sizeof(str) by sizeof(str[0]) to get the number of elements in the array
Explanation:
Introduction / Context:
This question checks your understanding of how arrays of pointers are represented in C and how the sizeof operator can be used to compute the number of elements in a statically defined array. The strings themselves are stored elsewhere; the array str contains pointers to those strings.
Given Data / Assumptions:
Concept / Approach:
In C, a statically declared array of N elements has a total size equal to N times the size of each element. Therefore N can be computed by dividing the total size by the size of one element. For an array of character pointers, this logic still applies, because the array elements are pointers all of the same type and size. The actual strings are stored elsewhere and do not affect the size of the pointer array.
Step-by-Step Solution:
Recognize that str is an array of six elements, each of type char pointer.
sizeof(str) returns the total array size in bytes, which is number of elements multiplied by size of each pointer.
sizeof(str[0]) returns the size of a single pointer element.
Dividing total size by element size, sizeof(str) / sizeof(str[0]), yields the number of elements in the array.
This count is also the number of strings referenced in the initializer list.
Verification / Alternative check:
On a 32 bit system, if pointers are 4 bytes, the array of six pointers has size 24 bytes. sizeof(str) is 24 and sizeof(str[0]) is 4, so 24 divided by 4 is 6, the number of strings. The calculation works similarly on systems with different pointer sizes.
Why Other Options Are Wrong:
Calling strlen(str) is incorrect because strlen expects a pointer to char and will treat the address of the first pointer as if it were a character string, which is not valid in this context.
Subtracting sizeof(str[0]) from sizeof(str) yields total size minus one element size, which has no direct meaning as a count.
Adding sizes and dividing by two is arbitrary and not based on how arrays are laid out in memory.
Common Pitfalls:
A frequent error is to apply strlen to the array name, confusing the array of pointers with a character array containing a single string. Another pitfall is to forget that this sizeof trick only works in the same scope where the array is declared; if str is passed to a function, it decays into a pointer and sizeof(str) would then give the pointer size, not the array size.
Final Answer:
You can compute the number of strings in the array by evaluating sizeof(str) / sizeof(str[0]), which gives the number of elements in the array.
Discussion & Comments