c - Why does printf literally print (null) and what exactly happens? -


in c programming exercise i'm doing (just simplifying):

printf( "%s", 0); 

the output is

(null) 

what happens here? assume printf interprets 0 char *, null? how replicate result like

char string[] = null; //compiler-error printf( "%s", string); 

?

firstly,

printf("%s", 0); 

leads undefined behavior (ub). %s in printf requires char * pointer argument. passing 0, int. alone breaks code,

printf("%s", 42);  

would. specific ub fact 0 zero not make difference.

secondly, if want attempt pass null-ponter %s format specifier, have like

printf("%s", (char *) 0); 

of course, leads undefined behavior well, since %s requires pointer valid string argument, , (char *) 0 not valid string pointer. implementations prefer handle such situations gracefully , print (null).

in particular case got lucky: printf("%s", 0) "worked" same way printf("%s", (char *) 0) , implementation saved day outputting (null).


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -