簡體   English   中英

取消引用 C 中的字符串文字有什么影響?

[英]What is the effect of dereferencing a string literal in C?

#include<stdio.h>

int main()
{
    printf("%c",*"abcde");
    return 0;
}

'a' 將如何成為該程序的 output? 讓我知道為什么 output 在 Turbo c 中編譯時是“a”......這里的“*”意味着什么?

"abcde"是一個字符串文字,它是一個字符數組( char[] )。 通常將其放在程序的只讀數據部分中。 如果將其傳遞給printf ,則編譯器實際上會將該數組的地址傳遞給printf

但是,在這里您要取消引用僅傳遞第一個字符的指針。

這是一個等效的,更詳細的版本,可能更有意義:

const char* str = "abcde";    // str is a char* pointer to "abcde"
char c = *str;                // De-reference that pointer - in other words,
                              //   get me the char that it points to.
printf("%c", c);              // Pass that char to printf, where %c is
                              //   expecting a char.

"abcde"是字符串文字,因此具有數組類型。 在除sizeof&的操作數之外的任何上下文中,數組都會衰減為其第一個元素的指針。 因此,當用作一元*運算符的操作數時, "abcde"被評估為在字符串開頭的指向“ a”的指針,並且*運算符取消引用該指針,從而獲得值'a' 將此值(整數)傳遞給printf以便使用%c格式說明符進行格式化會導致printf將對應的字符“ a”打印到stdout。

請記住 printf function 接受 const char* 作為參數,如上所述,字符串只是 char 值的數組。 在 c++ 中傳遞數組時,編譯器將其作為指向 [] 的第一個元素的指針。

前任。 string nums[] = {"one", "two); string* p2 = nums; //完全有效,編譯器如何看待這將是“one”的地址。

暫無
暫無

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

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