What is the output of the following program? #include <stdion.h> #include <string.h> main() { static char a[] = “Exforsys” printf(“%d”, *(a+ strlen(a))); }

The immediate answer one might give seeing the program would be 8 which is the length of the string “Exforsys”. But the output is not that. The wondering what would be the output. It is 0. Interesting at the same time strange to see the output is it not? The output is so because the strlen() function give the length of the string and in this case gives the length of “Exforsys” which is 8. Now if we see carefully the next statement namely the printf we can find that it is given to print the contents of the value at the 8th address from the base address.



E - Stored in base address a[0]

x - Stored in a[1]

f - Stored in a[2]

o - Stored in a[3]

r - Stored in a[4]

s - Stored in a[5]

y - Stored in a[6]

s - Stored in a[7]

‘’ - Stored in a[8]



Thus we find that in the 8th location from eth base address we have ‘’ which denotes the end of the string. The format specifier is %d for printing this so the ASCII value corresponding to ‘’ is 0 and this gets printed and thus the output of the above program is 0


So it is vital to know that each string is terminated by a ‘’ which denotes the end of string.

Questions by GeekAdmin   answers by GeekAdmin

Showing Answers 1 - 3 of 3 Answers

rishabh_aec

  • Feb 26th, 2007
 

In this program, consider the line


printf("%d",*(a+strlen(a)));

Here 'a' is the base address for the string a. It stores an address of a[0]. Now here in this case function strlen(a) will return the int value 8 (i.e. length o fthe string). It is added to base address i.e. 'a'. The result of this sum will be the address of the 9th character right after a[0]. As a[7] is the 8th and last character, thus 9th character will be null character i.e. '' (Null character). Now the VALUE AT operator i.e., * is used to access the value at specified address. Thus the statement :

*(a+strlen(a))

will return the value at that 9th memory location i.e. ''. As %d is used to print its integer value and the inter value (ASCII value) for ''(null char) is 0, therefore the output will be 0.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions