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
Why doesnt the call scanf work?
What are the 4 types of functions?
What Is The Difference Between Null And Void Pointer?
Create a simple code fragment that will swap the values of two variables num1 and num2.
What is an auto variable in c?
WHICH TYPE OF JOBS WE GET BY WRITING GROUPS .WHEN THE EXAMS CONDUCTED IS THIS EXAMS ARE CONDUCTED EVERY YEAR OR NOT.PLS TELL ME THE ANSWER
What is the difference between struct and typedef struct in c?
What are the different types of C instructions?
Explain argument and its types.
a value that does not change during program execution a) variabe b) argument c) parameter d) none
What type is sizeof?
Why can arithmetic operations not be performed on void pointers?
What is conio h in c?
What is a shell structure examples?
How can I invoke another program (a standalone executable, or an operating system command) from within a c program?