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.
It is very simple if you carefully look at your
printfcall.Here is the prototype of printf :
int printf(const char *format, ...);.printfexpects a pointer to format string as the first argument. In your program you are passing a pointer to this string :"20s"andprintfpromptly 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 :similarly
printf("%20s"+1,arr);is equivalent to :Because you are passing
"%20s"+1, the actual pointer which is passed to printf is pointing to a string"20s".