C Programming - Strings - Discussion
Discussion Forum : Strings - Find Output of Program (Q.No. 12)
12.
What will be the output of the program ?
#include<stdio.h>
#include<string.h>
int main()
{
static char s[] = "Hello!";
printf("%d\n", *(s+strlen(s)));
return 0;
}
Discussion:
38 comments Page 2 of 4.
Dipankar said:
1 decade ago
The expression *(s+strlen(s)) will yeild *(s+6), because s[]="hello!"; contains 6 characters, so the length is 6.
and the expression *(s+6)= s[6]. (acc. to pointers to array theory).
now in a strng the last element/bit always contains '\0'.
so, s[0]= 'H'
s[1]= 'e'
s[2]= 'l'
s[3]= 'l'
s[4]= 'o'
s[5]= '!'
s[6]= '\0'
hence the output gives zero value because ascii value of \0 is zero.
and the expression *(s+6)= s[6]. (acc. to pointers to array theory).
now in a strng the last element/bit always contains '\0'.
so, s[0]= 'H'
s[1]= 'e'
s[2]= 'l'
s[3]= 'l'
s[4]= 'o'
s[5]= '!'
s[6]= '\0'
hence the output gives zero value because ascii value of \0 is zero.
Shankra said:
1 decade ago
Thanks dipankar.
Prasad said:
1 decade ago
Thanks Dipankar your answer is so clear, I understood.
Nagababu said:
1 decade ago
Thank you dipankar.
Harshada said:
1 decade ago
Thank you dipankar.
Kannan said:
1 decade ago
@Dipankar explained well.
Omkar said:
1 decade ago
Thanks Dipankar for Good explanation
Sadanand said:
1 decade ago
Thanks priyanka.
Meghana said:
1 decade ago
strlen of hello! is 6. So expression in printf statement reduces to *(s+6). *(s+6) is same as s[6], which is null character. ASCII value for null character is 0. So it prints 0.
Subhankar Som said:
1 decade ago
strlen of Hello is 6. The expression *(s+strlen(s)) indicates *(s+6). According to pointers to array concept *(s+6)=s[6].
The last element contain '\0'. So the output gives 0 value as the value of \0 is 0(ASCII).
The last element contain '\0'. So the output gives 0 value as the value of \0 is 0(ASCII).
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers