asad_hussain
asad_hussain

Reputation: 2001

Why the following code gives this output?

I was tweaking with the printf() function.Since the printf() function takes a format specifier in order to recognize the datatype to print(Correct me if i'm wrong) the value of the datatype passed into it as argument,so I tried to do something like this---

#include<stdio.h>
int main()
{
char *f="%d";
char *g="asd";

printf(f,g);
return 0;
}

And the o/p is--

4210739

I am unable to understand why o/p is a number ?

Upvotes: 1

Views: 145

Answers (3)

Steve Summit
Steve Summit

Reputation: 47952

You said,

Since the printf() function takes a format specifier in order to recognize the datatype to print (Correct me if i'm wrong)

I'm not sure, but I think you may be a little wrong here.

When you call

printf(f, g);

the key thing to understand is that printf has no way of knowing the type of g.

When you call printf, it is your job to ensure that for every format specifier (that is, every % thingie) you use in the format string, you pass an argument of the correct type. For each %d in your format string, you must pass an int. For each %f in your format string, you must pass a double. For each %s in your format string, you must pass a char * pointing to a valid string. And so on.

In your code, you've got a %d in the format string, but instead of passing an int, you pass a char * pointing at a string. So you don't get the result you expect.

The %d wanted an int, but you didn't give it one. You passed a char *, but printf didn't know what to do with it. (If you had used %s, then printf would have known what to do with the char *.)

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

Because, your code invokes undefined behavior.

You're trying to print a string using %d format specifier. You should be using %s format specifier instead. Using wrong type of argument for a particular format (conversion) specifier invokes UB.

Quoting C11, chapter §7.21.6.1

[...] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

Change

char *f="%d";

to

char *f="%s";

Upvotes: 10

Anton Angelov
Anton Angelov

Reputation: 1244

As already stated, the %d specifier specifies that you will be passing a integer as second parameter and you pass a pointer (*char typed) variable instead. So the printf() routine interprets the pointer as an integer and prints it (it's value actually) as so.

To correctly output the string, you should use the %s specifier.

Upvotes: 4

Related Questions