edited by
16,668 views
49 votes
49 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$
edited by

8 Answers

1 votes
1 votes
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
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

9.1k
views
3 answers
44 votes
go_editor asked Feb 15, 2015
9,076 views
Consider the following two C code segments. $Y$ and $X$ are one and two dimensional arrays of size $n$ and $ n \times n$ respectively, where $2 \leq n \leq 10$. Assume th...
12.1k
views
4 answers
41 votes
go_editor asked Feb 16, 2015
12,142 views
Consider the following C program:#include<stdio.h int f1(void); int f2(void); int f3(void); int x=10; int main() { int x=1; x += f1() + f2 () + f3() + f2(); printf("%d", ...
22.9k
views
1 answers
77 votes
go_editor asked Feb 16, 2015
22,910 views
Consider the following C program:#include<stdio.h int main() { int i, j, k = 0; j=2 * 3 / 4 + 2.0 / 5 + 8 / 5; k-= j; for (i=0; i<5; i++) { switch(i+k) { case 1: case 2: ...
23.1k
views
11 answers
62 votes
go_editor asked Feb 15, 2015
23,076 views
Consider the following C program#include<stdio.h int main() { static int a[] = {10, 20, 30, 40, 50}; static int *p[] = {a, a+3, a+4, a+1, a+2}; int ptr = p; ptr++; print...