Consider the following function definition.
int fX(char *a) {
char *b = a;
while (*b)
b++;
return b - a; }
Which of the following statements is/are TRUE?
View worked solution
Answer: A;B;D
Let us analyze the given C function:
int fX(char *a) {
char *b = a;
while (*b)
b++;
return b - a;
}
Function Analysis:
- The function takes a character pointer
apointing to the start of a null-terminated string. - It initializes another character pointer
btoa. - The loop
while (*b) b++;increments the pointerbuntil it points to the null terminator ('\0'), which has an ASCII value of0(evaluating to false). - Finally,
b - aperforms pointer subtraction, which returns the number of elements betweenbanda. This is equivalent to the length of the string (similar to the standardstrlen()function).
Evaluating the Options:
- Option A:
"a b c d"is a string literal. In C, string literals are automatically null-terminated. Thus, the function will successfully traverse the string and return its length (7). This statement is TRUE. - Option B:
char c[] = "abcd"creates a character array initialized with{'a', 'b', 'c', 'd', '\0'}. When passed tofX(c), the array decays to a pointer to its first element. Since it is null-terminated, the function will successfully return 4. This statement is TRUE. - Option C: The code is syntactically correct and standard C. It will compile without any errors. This statement is FALSE.
- Option D:
char *c = "abcd"declares a pointer pointing to a null-terminated string literal in the read-only data segment. Passing this pointer tofX(c)will successfully return 4. This statement is TRUE.
Free practice · Your answers on this page are not saved.
