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

Why doesnt the call scanf work?

668


What are the 4 types of functions?

571


What Is The Difference Between Null And Void Pointer?

640


Create a simple code fragment that will swap the values of two variables num1 and num2.

810


What is an auto variable in c?

754






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

1461


What is the difference between struct and typedef struct in c?

657


What are the different types of C instructions?

678


Explain argument and its types.

602


a value that does not change during program execution a) variabe b) argument c) parameter d) none

694


What type is sizeof?

585


Why can arithmetic operations not be performed on void pointers?

590


What is conio h in c?

622


What is a shell structure examples?

589


How can I invoke another program (a standalone executable, or an operating system command) from within a c program?

653