2013-11-22 29 views
1

的輸出,我學習C語言和套牢問題如下:發現C程序

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

請解釋什麼是這個程序的輸出。 謝謝。

+0

輸出是'd'。 –

+0

@JoachimPileborg,請解釋一下。 –

+0

你可能想了解一下[pointer arithmetics](http://stackoverflow.com/questions/394767/pointer-arithmetic)。 –

回答

4

讓我們來看看它的另一種方式:

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

輸出是「d」,因爲「字符串」是一個指針,它指向的「%」的地址。如果你將這個指針加1,得到'newString',它將指向字符'd'。這就是爲什麼輸出是'd',而printf基本上放棄了第二個參數。

存儲器佈局是以下(注意終止零字符「\ 0」):

[%] [d] [\0] 
^ ^
| | 
| newString 
string 
+0

Thanx的答案 –

6

"%d"const char*指向的"%d"第一個字符。

"%d" + 1const char*,它指向"%d"的第二個字符(即字符串"d")。

通過"d"格式爲printf打印d,無論您傳遞給printf的附加參數如何。

+0

Thanx的解釋 –