in Programming in C edited by
15,999 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

64 votes
64 votes
Best answer
p = s1 + 2;

Type of s1 is char[7] and sizeof *s1 is sizeof (char) = 1. So, s1 + 2 will return address in s1 + 2 *sizeof(char) = address in s1 + 2. So,  $p$ now points to the third element in s1.

*p = '0';

The third element in s1 is made $0$. So, $1234$ becomes $1204$. C choice. 

edited by
by

4 Comments

Great Explanation. Helped a lot in cracking the confusion.
0
0
I still didn't get it when we declared the array of characters as s1[7], we wasted the memory because we used only 4 characters and a null at last.

so they did it purposefully in the question?
0
0
42 votes
42 votes

Answer is C.
For the confused people,   
*p = '0';    So answer is 1204
If *p = 0;   Here answer will be 12

0 means Ascii 0  which is Null character.

'0'  means Ascii 48 which is character '0'
 

edited by
by

9 Comments

If *p = 0, then will there be an error? As integer value is assigned to char variable.
1
1
No, a char can hold upto 255.
1
1
@Ahwan

NULL has nothing to do with strings, it is a macro defined in stddef.h

'\0' has ascii value of 0 which is used at the end of each string
0
0
Is it fine now?
0
0
Yes.
0
0

@  your answerer confused me

what is the difference between *p = '0'  &  *p = 0. I can't understand.

please reply

0
0

*p = '\0' will also print  12

this assumption  is wrong because there is nothing like character '\0' in and may lead to error as we assigning 2 char in one location.

Am I right  @Arjun Sir?

1
1
No. \0 is a valid character as \ is an escape character and it's ASCII code is 0.
4
4
Anything which can be stored in 1Byte is called as char. Computer understands this only. Although we are able to see that 0 is integer. But computer checks whether the thing can be stored in 1 byte or not..
0
0
8 votes
8 votes
Here s1 is an array, So s1 points to base address.

so , p=s1+2 will point to 3rd element of s1.

and *p='0'

value at p (Which is the third element of s1) , so 1234 becomes 1204.
1 vote
1 vote
1204 will be correct answer.
by
Answer:

Related questions