Consider the following C program segment: char p[20]; char *s = "string"; int…

2004

Consider the following C program segment:

char p[20];
char *s = "string";
int length = strlen(s);
int i;
for (i = 0; i < length; i++)
     p[i] = s[length — i];
printf("%s",p);

The output of the program is (GATE CS 2004)

  1. A.

    gnirts

  2. B.

    gnirt

  3. C.

    string

  4. D.

    no output is printed

Attempted by 20 students.

Show answer & explanation

Correct answer: D

Key insight: the code writes the string's terminating null character into p[0], so p becomes an empty string and printf prints nothing.

  • For s = "string", length = strlen(s) = 6.

  • When i = 0 the code does p[0] = s[length - i] i.e. p[0] = s[6]. s[6] is the terminating null '\0'.

  • Because p[0] is '\0', p is an empty string even if later iterations write other bytes into p[1..]. printf with "%s" prints up to the first '\0', so nothing is printed.

  • Accessing s[length] is defined (it gives '\0'), and writing into p is within bounds for p[20], so the behavior here is well-defined and results in no output.

Corrected code:

char p[20]; char *s = "string"; int length = strlen(s); int i;

for (i = 0; i < length; i++)

p[i] = s[length - 1 - i];

p[length] = '\0';

printf("%s", p);

With this correction the output will be: gnirts

Explore the full course: Gate Guidance By Sanchit Sir