Reputation:
I have a simple program which is supposed to print a string. But I am not getting the expected output. Can anyone tell me what is wrong with the program ?
Here is my code:
main()
{
char arr[] = "Test_string";
printf("%20s"+1,arr);
return 0;
}
output: 20s
Expected output is:Test_string
"Test_string"
getting printed in 20 places as we are giving "%20s"
as format specifier.
Upvotes: 2
Views: 278
Reputation: 2335
It is very simple if you carefully look at your printf
call.
Here is the prototype of printf : int printf(const char *format, ...);
.
printf
expects a pointer to format string as the first argument. In your program you are passing a pointer to this string : "20s"
and printf
promptly prints what you are passing.
Let me explain why the pointer passed is pointing to "20s"
and not "%20s"
.
Quoted strings in C are interpreted as character pointers.
Character arrays which, when passed to a function, decay into a pointer.
printf("%20s",arr);
is equivalent to :
const char * ptr = "%20s";
printf(ptr,arr);
similarly printf("%20s"+1,arr);
is equivalent to :
const char * ptr = "%20s";
printf(ptr+1,arr);
Because you are passing "%20s"+1
, the actual pointer which is passed to printf is pointing to a string "20s"
.
Upvotes: 6
Reputation: 170193
Remove the +1 next to the format string
printf("%20s",arr);
Upvotes: 3