[英]Explain the strange output ''
您使用的所有printf()
調用都是不正確的,除了第二個,因為相對參數或使用的轉換說明符是錯誤的。
這會調用未定義的行為:
引自 C18, 7.21.6.1/9 - “fprintf 函數”:
“如果轉換規范無效,則行為未定義。288) 如果任何參數不是相應轉換規范的正確類型,則行為未定義。 ”
printf("%c\n",p);
當您嘗試打印指針指向的 object 的值時,您必須在指針 object 之前使用取消引用運算符 ( *
)。 否則,您嘗試打印指針的值 - 指針指向的 object 的地址。 由於此操作,您使用錯誤的轉換說明符%d
而不是%p
來打印指針的值。
更正后的程序是:
#include<stdio.h>
int main(void)
{
char c[]= "Suck It Big";
char *p = c;
printf("%c\n", *p); // Prints the first element of array c.
printf("%c\n", p[3]); // Prints the fourth element of array c
printf("%c\n", *(++p)); // Prints the second element of array c
printf("%p\n", (void*) p); // Prints the address held in p / first element of c.
printf("%p\n", (void*) &p[3]); // Prints the address of the fourth element of c.
}
請注意,要使程序符合 C 標准,必須強制轉換為void*
。
Output:
S
k
u
0x7fff1d3a133d // Address defined by system
0x7fff1d3a1340 // Address defined by system
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.