簡體   English   中英

解釋奇怪的output''

[英]Explain the strange output ''

我用 C 語言編寫了代碼,

#include<stdio.h>

int main(void)
{
    char c[]="Suck It Big";
    char *p=c;
    printf("%c\n",p);
    printf("%c\n",p[3]);
    printf("%c\n",++p);
    printf("%d\n",p);
    printf("%d\n",p[3]);
}

我得到的這個代碼的 output 是:
輸出

我復制了 output 的第 1 行和第 3 行的奇怪字符並將其粘貼到編輯器上,得到了這個“ DLE ”。 任何人都可以解釋這個的含義。

您使用的所有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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM