簡體   English   中英

指向字符數組輸出的指針

[英]Pointer to character array output

當我們聲明一個指向任何整數的指針時,說我們聲明它像

int i=5;
int *p=&i;

我們使用*p來獲取值 5,如果我們想要地址,我們使用不帶星號的p來獲取地址。 但是在字符數組的情況下,當我們說

char *str="HELLO";

我們只是使用str來獲取"HELLO"作為 printf 函數的輸出。 像這樣,

printf("%s",str);

這里我們使用了不帶星號的str

當我們使用不帶星號的指針變量時,為什么我們沒有獲得地址,而是在此處獲得“HELLO”作為輸出,而在指向整數的指針的情況下獲得地址?

好的,首先int *p=5; 是錯的! 你不能在指針的聲明中做到這一點。 那時指針需要一個地址。 你應該做int *p; 然后*p = 5; 為其賦值。

printf("%s",str); // prints the value of the variable, because its a pointer.
printf("%s",*str); // the * will cause to a segmentation fault

int *p // the * there is just used to tell the compiler that you are declaring a pointer of type integer.

/* another scope after declaring your pointer */

*p //is used to get value of a pointer variable.(dereference it)
&p //is used to get the adress of a pointer variable.
p //contains an adress.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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