working of printf in C

Can anybody please explain me the output of following code

char *str="ABCDE" ;
printf(str,"%s \\n ");



thanx in advance

Well, the printf(str,"%s \n "); is wrong since if you want to print out to a string you should use sprintf() also declared in stdio.h. Anyway, writing to a pointer that points to Data segment would result to Segmentation fault most likely, since no space is reserved for the str… This would be right

char str[MAX_STRING], *str2 = "world";
sprintf(str,"Hello %s\n", str2);

printf(str) give you “Hello world”.
Anyway, more on printf(), sprintf(), fprintf() can be found on

Kindest regards,
Petar Vukmirovic

The first printf -

printf(str,"%s \\n ");

has first argument as str which does not contain any format specifier (like “%d”, “%s” etc.), so the second argument is simply discard. Hence contents of str are printed i.e ABCDE -[1]

In second printf -


there is “%s” specifier, hence the second argument (str) is printed. - [2]

Notice there are double slashes before n, hence the first slash escapes the second slash, hence “\n” is printed at the end. -[3]

Combining [1], [2] and [3] we get the output - ABCDEABCDE\n

1 Like