2015-10-13 354 views
-5

我試圖按照書中的一些步驟。這是書中的確切代碼,但我收到了一條錯誤消息。如何使用C和printf函數打印指針內部的內容?

這兩個printf語句的是問題:

printf(pointer); 
printf(pointer2); 

如何解決這個實際打印什麼是裏面的指針?

#include <stdio.h> 
#include <string.h> 

int main(void) 
{ 
    char str_a[20]; //A 20-element array 
    char *pointer; //A pointer, meant for a character array 
    char *pointer2; //And yet another one 

    strcpy(str_a, "Hello World\n"); 
    pointer = str_a; //Set the first pointer to the start of the array 
    printf(pointer); 

    pointer2 = pointer + 2; //Set the second one 2 bytes further in. 
    printf(pointer2); 
    strcpy(pointer2, "y you guys\n"); //Copy into that spot. 
    printf(pointer); 
    return 0; 
} 
+2

的printf( 「%S」,str_a)?但請注意,如果以這種方式使用printf是一種安全風險。讓舒爾str_a總是終止。 – EGOrecords

+1

使用'printf(「%s」,pointer_variable);'或'fputs(pointer_variable,stdout);' – BLUEPIXY

+0

謝謝你們兩位,這些答案是快速和準確的。 @BLUEPIXY,我用你的方法,它的工作。 – Mekanic

回答

1

嘗試

printf("%s", str_a); 

現在,如果你想打印變量本身的地址,你可以嘗試:

int a = 5; 
printf("%p\n",(void*)&a); 
+0

我打印了變量本身的地址。有趣。 – Mekanic

0

使用

printf("%s", str_a); 

它將打印你的str_a。但請記住,C中的每個char * -string都必須以\0-字符結尾。如果沒有終止,那麼在字符串後面的所有內容也會被打印和訪問。

在最好的情況下,這會導致SIGSEGV,並且程序終止。在最壞的情況下,有人可以使用它來打印存儲在您試圖打印的字符串旁邊的RAM中的明文密碼數據。

閱讀「緩衝區溢出」和「堆棧溢出」。

如果通過

const char* str = "Hello World"; 

定義串,則C將自動添加\0字符爲你,並且該字符串的實際長度是12個字節(11個字符)。

但是,如果你通過strcpy或通過從stdin或從任何不受信任的來源(如網絡)閱讀它,那麼你有安全漏洞。

但只是爲了測試printf("%s", str_a)就好了。

爲printf的其它參數是:

d or i Signed decimal integer 392 
u Unsigned decimal integer 7235 
o Unsigned octal 610 
x Unsigned hexadecimal integer 7fa 
X Unsigned hexadecimal integer (uppercase) 7FA 
f Decimal floating point, lowercase 392.65 
F Decimal floating point, uppercase 392.65 
e Scientific notation (mantissa/exponent), lowercase 3.9265e+2 
E Scientific notation (mantissa/exponent), uppercase 3.9265E+2 
g Use the shortest representation: %e or %f 392.65 
G Use the shortest representation: %E or %F 392.65 
a Hexadecimal floating point, lowercase -0xc.90fep-2 
A Hexadecimal floating point, uppercase -0XC.90FEP-2 
c Character a 
s String of characters sample 
p Pointer address b8000000 
n Nothing printed. 

(來源http://www.cplusplus.com/reference/cstdio/printf/

您可以使用這些參數,如:

printf("%i: %f and i am a Character: [%a]", 10, 4.4, (char)a); 
+0

哇,這是一些有趣的東西。我讀了一些關於緩衝區溢出的知識,並認爲它是一個非常好的東西,特別是作爲C程序員而知道。感謝您抽出寶貴時間傳遞我非常感謝的信息。再次感謝。 – Mekanic

+0

那麼,如果你接受這個答案作爲解決問題的答案,那就太棒了! – EGOrecords