Question

Consider the following C program segment.

#include <stdio.h>
int main()
{
    char s1[7] = "1234", *p;
    p = s1 + 2;
    *p = '0';
    printf("%s", s1);
}

What will be printed by the program?

Choose one option
Official answer and solution
Official answer
C
From
Official GATE 2015 answer key

Solution

Trace pointer arithmetic and character array modification in C.

Step-by-step execution:

  1. char s1[7] = "1234", *p; allocates an array of 7 characters and initializes it with the null-terminated string "1234":
    • s1[0] = '1'
    • s1[1] = '2'
    • s1[2] = '3'
    • s1[3] = '4'
    • s1[4] = '\0'
    • s1[5] = '\0'
    • s1[6] = '\0'
  1. p = s1 + 2; computes the address of index 2, so p points to s1[2].
  2. *p = '0'; assigns the ASCII character '0' (value 48) to s1[2], replacing character '3'.
    Note that '0' is an ordinary printable digit character, not the null terminator \0 (value 0).
  1. The contents of s1 are now '1', '2', '0', '4', \0.
  2. printf("%s", s1); prints the string starting from s1[0] until it encounters \0, producing 1204.
Final answer

C

Common trap

Confusing character '0' with the null terminator '\0'. If '\0' were assigned, the output would be 12; but since '0' is assigned, the output is 1204.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2015 Computer Science and Information Technology (CS) Session 3
Question
17 of 65, printed as CS Q.7
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.