C Programming - Pointers - Discussion

Discussion Forum : Pointers - Find Output of Program (Q.No. 7)
7.
What will be the output of the program ?
#include<stdio.h>

int main()
{
    char *str;
    str = "%s";
    printf(str, "K\n");
    return 0;
}
Error
No output
K
%s
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
57 comments Page 4 of 6.

Ravi said:   1 decade ago
@Kavya and others:Your concept is correct but then also it somehow depends on the arguments of printf() function ,if its just replacing the string then how come the following does not work ?

int main()
{
char s[]="goog";
printf(s);
return 0;
}

Kartik said:   1 decade ago
Why is the need for this kind of format: printf ("%s", "hello").
If we can simply print using: printf ("hello") ;.
TAKE A MOMENT Please!

Mrutyunjay said:   1 decade ago
It is just like when we print hello wotld as
printf ( "%s", "hello world\n" ) Output will be hello world, similarly printf ( "%s", "k\n" ) ; output will be k itself..

Priya said:   1 decade ago
#include<stdio.h>

int main()
{
char *str;
str = "hi %s hello";
printf(str,"hh");
return 0;
}

Here printf function take the address of str it is pointing to the "hi %s hello"

it's print hi hh hello
%s will take address of hh

printf("%s")
it will print null

printf("%s","hi");
it's print hi

It takes address of string. Hope you are understand.

Sree said:   1 decade ago
Hai kavyashree.

Printf ("%s", "k\n") ; why %s is not shown as output which in double quotes. Only k as output.

Preeti said:   1 decade ago
@kavyashree.

You are absolutely right.

Santhosh said:   1 decade ago
Hey rajat in turbo it is working properly.

Rajat said:   1 decade ago
It shows error in turbo c compiler. "declaration syntax error".

Raghu said:   1 decade ago
The printf() is a function which receives a pointer to a format string.
printf(str, "K\n"); --> works because it passes the address of format string -> "%s"

It is as good as specifying
printf("%s", "K\n") which again passes pointer to string "%s".

So, there is not replacement of string is happening here ( as mentioned by Kavyashree) just a pointer which is passed across.

Nagraj said:   1 decade ago
@Alim

printf("%c\n", str);
in this statement why it prints "$"


Post your comments here:

Your comments will be displayed after verification.