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 2 of 6.

Arvindh said:   1 decade ago
Kartik : I had the same doubt. However both work. You don't need the type as prefix in printf statement if you're directly printing something, but if you are printing a value stored in a variable it needs the type of the variable.

Pranoy said:   1 decade ago
@KavyaShree@Hann

Dont worry Kavya your assumption is absolutely.

The code what You have written is true.

And, Hann it is not necassary to ask a variable to print the data type, since it takes as null if not assigned

Ravindra bagale said:   1 decade ago
@Everyone.

Very simple logic. Just replaces the string, nothing is else. Just assigns "%s" to str. If you uses %d then it will gives some integer result, if %c then some character. Don't take tension, just chill guys.

Kavyashree said:   1 decade ago
Its because

The statement printf(str, "K\n"); is replaced with printf("%s" , "K\n");
// since str = "%s";

So it will print K.

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..

Sachin said:   9 years ago
If we try to print only str it will show (null) as output and in the code, there is no need of str.
It is only taking printf(" ");
Whatever you write inside the quotes is only printing that's it.
(2)

Kaushlenda singh parihar said:   1 decade ago
Hoping this example will help you understand the concept used in above question.

#include<stdio.h>
int main()
{char *str = "%d";
int i=10;
printf(str,i);
return 0;
}

Output:10.

Hann said:   1 decade ago
Its like
char str[]="good";
printf("%s",str);
its jst like replacing str with "good"
it becomes printf("%s","good");
output will be:
good
(1)

Bhavesh said:   1 year ago
str has "%s" stored in it so the printf will work like,
printf(Str,"K\n"); => printf("%s","K\n"); => will print K as it's string and \n is for newline.
(6)

Ranjan said:   1 decade ago
@Kavyashree
your assumption is wrong, as it will ask a variable to print the data type, by the way the code offered from you shows error.


Post your comments here:

Your comments will be displayed after verification.