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

How are structure passing and returning implemented?

588


Explain how do you determine whether to use a stream function or a low-level function?

619


What are the two types of functions in c?

562


What is unary operator?

656


Why do we use return in c?

564






What are pointers? What are different types of pointers?

622


Explain how do you determine a file’s attributes?

588


What is the difference between %d and %i?

592


Write a code to determine the total number of stops an elevator would take to serve N number of people.

725


What is variable declaration and definition in c?

497


Can you mix old-style and new-style function syntax?

660


How can you read a directory in a C program?

647


What are the string functions? List some string functions available in c.

600


How can I direct output to the printer?

808


What is null pointer constant?

592