GATE CS 2024 Set 2 — Question 33

MSQ+1 / -0MediumPointers & Pointer ArithmeticC ProgrammingProgramming & Data StructuresArrays & Strings in C

Programming & Data Structures → C Programming → Arrays & Strings in C

Last updated

Question

Consider the following C function definition.
int fX(char *a){
char *b = a;
while(*b)
b++;
return b - a;}
Which of the following statements is/are TRUE?
A.
The function call fX("abcd") will always return a value
B.
Assuming a character array c is declared as char c[] = "abcd" in main(), the function call fX(c) will always return a value
C.
The code of the function will not compile
D.
Assuming a character pointer c is declared as char *c = "abcd" in main(), the function call fX(c) will always return a value

Correct answer

(A) The function call fX("abcd") will always return a value; (B) Assuming a character array c is declared as char c[] = "abcd" in main(), the function call fX(c) will always return a value; (D) Assuming a character pointer c is declared as char c = "abcd" in main(), the function call fX(c) will always return a value

Solution

The function fXfX is a standard implementation of the string length function (strlen). It operates as follows:
1.It initializes a pointer bb to the start of the string aa.
2.It iterates through the memory using a while loop until it encounters the null terminator (\0).
3.It returns the difference between the final pointer position and the initial pointer position (bab - a), which corresponds to the number of characters in the string.
Evaluating the options:
  • Option (A): "abcd" is a string literal. In C, string literals are stored in a read-only data segment and are automatically null-terminated. Passing this to fXfX is valid, and the function will return 4. Thus, it will always return a value.
  • Option (B): char c[] = "abcd" declares a local character array and initializes it with the characters 'a', 'b', 'c', 'd', and '\0'. This is a valid null-terminated string. Passing it to fXfX will return 4. Thus, it will always return a value.
  • Option (C): The code is syntactically correct C. It uses valid pointer arithmetic and standard control flow. It will compile without errors.
  • Option (D): char *c = "abcd" makes cc point to the first character of the null-terminated string literal "abcd". Passing this pointer to fXfX will return 4. Thus, it will always return a value.
Since statements (A), (B), and (D) are correct, the answer is A, B, and D.

More questions on C Programming

Practice GATE CS PYQs with adaptive difficulty

Timed practice, skill tracking, and AI explanations — free to start.

Start practicing free