in Programming in C edited by
15,982 views
46 votes
46 votes

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?

  1. $12$
  2. $120400$
  3. $1204$
  4. $1034$
in Programming in C edited by
16.0k views

3 Comments

One more key learning here.

If it would have been char *s= "1234", then it will be stored as a string constant in the data segment(read-only). we cannot change the content of string using another pointer. It will give an error.
31
31
1204 is answer.
0
0

in simple terms initially p was pointing to 1 later it was pointing to 3 and then was asked to change 3 → 0 via this line *p = '0';  after this modification, when you print s1, it will display "1204".

0
0

8 Answers

1 vote
1 vote
s1[7]="1234"

p=s1+2

it is pointing to the address of "3" of "1234"

if *p=0 then the value of 3 replaced by 0

so the printf("%s", s1) prints 1204

1 comment

if *p=0 then the output will be 12 only.

because 0 acts as Null here and printf will print until NULL character.

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

 

output=====1204

because ASCII value of 48 is 0

https://theasciicode.com.ar/ascii-printable-characters/number-one-ascii-code-49.html#:~:text=To%20get%20the%20letter%2C%20character,%221%22%20in%20ASCII%20table.
0 votes
0 votes

Here it should have given char *s1, but still the s1[7]=1234 can be answered as s1 meaning the element 1 in the array which is 2 and then 2 is added with s1 so it goes to 4 th element in the array. So *s1=sizeof(char)=1.  s1+2*sizeof(char)= address in s1+2 so now we have to replace the 3rd element with 0 as *p is now pointing to the 3rd element in the array   So 1234 is replaced by 1204 Hence C i the ans.

0 votes
0 votes
*p = s1+2 refers to 3rd element in the array which is 3 and we are changing 3 to 0 ,  

So when we run printf("%s",s1) it will print the entire array s1 .

Now when we run printf("%s",p) it will print 04 because the p pointer is pointing to the 3rd element and it will print from there to the last element .
Answer:

Related questions