Skip to content
Official PYQ · 2024

GATE CS 2024 Set 2 Q23 — Programming in C

Explain with AI

​​​Consider the following C\mathrm{C} function definition.

int fX(char *a) {

char *b =  a;

while (*b)

b++;

return b - a; }

Which of the following statements is/are TRUE?

Select all correct options
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 a pointing to the start of a null-terminated string.
  • It initializes another character pointer b to a.
  • The loop while (*b) b++; increments the pointer b until it points to the null terminator ('\0'), which has an ASCII value of 0 (evaluating to false).
  • Finally, b - a performs pointer subtraction, which returns the number of elements between b and a. This is equivalent to the length of the string (similar to the standard strlen() 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 to fX(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 to fX(c) will successfully return 4. This statement is TRUE.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions