繁体   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