Reason for Exit

#include<stdio.h> int main(void) { int a=5; printf("%d"+1,a); } 

Output: d. I did not understand how the exit goes: d?

+4
source share
6 answers

You have transferred the first argument printf "%d"+1 ; "%d" actually considered as const char * , which points to the memory location where %d is stored. Like any pointer, if you increment it by one, the result will point to the next element, which in this case will be d .

a not used, but this should not be a problem, since in general ( I don’t know if it meets the standard requirements of Edit: yes, this, see below), the responsibility for clearing the stack for variable functions depends on the caller (at least cdecl does it this way , it may or may not be UB, I don't know *).

You can see it easier:

 #include<stdio.h> int main(void) { int a=5; const char * str="%d"; printf(str + 1, a); } 

 str ---------+ | V +----+----+----+ | % | d | \0 | +----+----+----+ str + 1 ----------+ | V +----+----+----+ | % | d | \0 | +----+----+----+ 

Thus, ( "%d"+1 ) (which is "d" ) is interpreted as a format string, and printf , finding no % , simply prints it as is. If you want to print the value of a plus 1 instead, you should have done

 printf("%d", a+1); 


Change * ok, this is not UB, at least for the C99 standard (Β§7.19.6.1.2), to have unused parameters in fprintf :
If the format is exhausted while the arguments remain, the redundant arguments (as always), but otherwise ignored.

and printf defined as the same behavior in Β§7.19.6.3.2

The printf function is equivalent to fprintf with the stdout argument before the printf arguments.
+24
source

String literals are pointers. When moving the pointer to "%d" by 1, the result is "d" . The argument is discarded.

+12
source

You must do printf("%d", a+1) . "%d" + 1 is a pointer to "d" inside the char array ( {'%','d','\0'} ).

+2
source

Because of +1 . If you want to increase a do: printf("%d", a + 1); .

+1
source

Suppose you had:

 char x[] = "%d"; 

What do you expect

 printf(x + 1, a); 

for print?

Hint: tc: 5: warning: too many arguments for format

+1
source

"% d" is a String constant, it will be stored in memory char [] in memory. At run time, "% d" returns the initial location of char []. Increasing the character array pointer by one indicates the next character. Therefore, only "d" is passed to the printf function. therefore the output is "d"

0
source

All Articles