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
How are structure passing and returning implemented?
Explain how do you determine whether to use a stream function or a low-level function?
What are the two types of functions in c?
What is unary operator?
Why do we use return in c?
What are pointers? What are different types of pointers?
Explain how do you determine a file’s attributes?
What is the difference between %d and %i?
Write a code to determine the total number of stops an elevator would take to serve N number of people.
What is variable declaration and definition in c?
Can you mix old-style and new-style function syntax?
How can you read a directory in a C program?
What are the string functions? List some string functions available in c.
How can I direct output to the printer?
What is null pointer constant?