An interesting behaviour in printf

Tim_CDC_Roberts at cup.portal.com Tim_CDC_Roberts at cup.portal.com
Sat Mar 18 03:47:57 AEST 1989


In <960 at Portia.Stanford.EDU>, joe at hanauma (Joe Dellinger) asks:

> What would you expect the following program to print out?
>
>
>	#include <stdio.h>
>	main()
>	{
>	char string[10];
>	string[0] = '*';
>	string[1] = '\0';
>	printf("%s\n", string[1]);
>	}
>
> Just "\n", right? On our system it prints out "(null)\n"!!!

No, I expect it to print out (null)\n.  The '%s' format item expects to
find a pointer_to_char on the stack.  By specifying string[1], you have
passed a _char_.  This _char_ happens to have the value 0.  When printf
goes to use this as a pointer, it finds that it is a null pointer.  To
do what you expected, replace the printf with:
        printf("%s\n", &string[1]);
                       ^

Trivia question: is the '(null)' output of printf standard or widespread?
I know that Microsoft C does this; do other compilers?

Tim_CDC_Roberts at cup.portal.com                | Control Data...
...!sun!portal!cup.portal.com!tim_cdc_roberts |   ...or it will control you.



More information about the Comp.lang.c mailing list