簡體   English   中英

static const char* VS const char* 在 C

[英]static const char* VS const char* in C

C 中的 const const char*static const char*有什么區別?

我認為static const char* 和 const char* 之間的差異的答案是錯誤的。

事實上, const char*元素放在程序的.rodata部分中,否則以下將導致段錯誤:

const char* f() {
    const char* hello = "hello";
    return hello;
}

int main() {
    const char* hello_after = f();
    printf("%s\n", hello_after);
}

實際上,因為該代碼有效,所以f返回的指針仍然指向活動數據,這表明該數據不是在堆棧上分配,而是存儲在.rodata中。

但是,在我看來,就 GCC 而言, const char*static const char*是一樣的。

但是,為什么const int*static const int*的行為不一樣? 這是一個例外,在 GCC 中硬編碼,僅對於char類型,然后conststatic const應該相同?

非常感謝您的幫助!

在此 function 聲明中

const char* f() {
    const char* hello = "hello";
    return hello;
}

指針 hello 指向具有 static 存儲持續時間的字符串文字“hello”。 也就是說,它不是具有 static 存儲持續時間的指針,而是具有 static 存儲持續時間的指向文字。 在每次調用 function 時,都會重新初始化指針。

如果您要聲明 function 之類的

const char* f( ) {
    static const char* hello = "hello";
    return hello;
}

那么在這種情況下,指針本身具有 static 存儲持續時間。 它在程序獲得控制權之前被初始化一次,並且它的值被保存在 function 調用之間。

例如考慮這個演示程序。

#include <stdio.h>

const char* f( int i ) 
{
    static const char* hello = "hello";

    if ( i == 1 ) hello = "bye";
    else if ( i == -1 ) hello = "hello";

    return hello;
}

int main(void) 
{
    puts( f( 0 ) );
    puts( f( 1 ) );
    puts( f( 0 ) );

    return 0;
}

它的 output 是

hello
bye
bye

最初,指針 hello 由字符串文字“hello”初始化。

然后由於這個電話

    puts( f( 1 ) );

它的值被改變了。 現在它指向字符串文字“再見”。

第三次通話

    puts( f( 0 ) );

指針保留之前調用 function 分配給它的值。

這是由於指針具有 static 存儲持續時間。

暫無
暫無

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

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