What will be the result of the following program?
main()
{
char p[]="String";
int x=0;

if(p=="String")
{
printf("Pass 1");
if(p[sizeof(p)-2]=='g')
printf("Pass 2");
else
printf("Fail 2");
}
else
{
printf("Fail 1");
if(p[sizeof(p)-2]=='g')
printf("Pass 2");
else
printf("Fail 2");
}
}

a) Pass 1, Pass 2
b) Fail 1, Fail 2
c) Pass 1, Fail 2
d) Fail 1, Pass 2
e) syntax error during compilation

Answer Posted / jaroosh

Fail 1 , Pass 2.

Some explanation,
1. Fail 1
first of all, to compare strings in C, you use this strcmp
function, so this WOULD give PASS 1 :
if(strcmp(p,"String") == 0)
but
if(p=="String")
will fail because this line means :
if address of p is the same as address of some temporary
storage for literals, where literal "String" is stored,
which is very rarely true, because storing literals is
compiler specific and is very hard to estimate at runtime.
2. Pass 2
sizeof(p) gives 7, because sizeof(char) is 1 byte, and we
have 7 chars in array storing "String", which are :
[0]S
[1]t
[2]r
[3]i
[4]n
[5]g
[6]\0 (EOS)
now, clearly sizeof(p) - 2 is [5] which is "g"
thats why
if(p[sizeof(p)-2]=='g')
is true.

Is This Answer Correct ?    10 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Is int a keyword in c?

728


Why do we use pointer to pointer in c?

801


Are pointers integers in c?

799


What is the difference between array and structure in c?

776


Explain the use of bit fieild.

902


What is the difference between union and anonymous union?

1038


What does dm mean sexually?

1037


how much salary u want ? why u join in our company? your domain is core sector why u prefer software ?

1722


What is dynamic dispatch in c++?

767


Are local variables initialized to zero by default in c?

749


What is masking?

893


What is 1d array in c?

842


to find the closest pair

2051


How can a number be converted to a string?

896


a way in which a pointer stores the address of a pointer which stores the value of the target value a) reference b) allocation c) multiple indirection d) none

862