简体   繁体   English

复合文字中的字符串文字

[英]String literal in compound literal

I have a question about string literals inside compound literals.我对复合文字中的字符串文字有疑问。

As the lifetime of the struct S compound literal is inside the block surrounding the func call, I wonder if it still alright to use the name pointer inside the global gs variable.由于 struct S 复合文字的生命周期在 func 调用周围的块内,我想知道在全局 gs 变量内使用名称指针是否仍然可以。 I guess the string literal "foo" is not bound to the lifetime of the compound literal but rather resides in.rodata?我猜字符串文字“foo”没有绑定到复合文字的生命周期,而是驻留在.rodata 中? Is that right?是对的吗? At least gs.name still prints foo.至少 gs.name 仍然打印 foo。

#include <stddef.h>
#include <stdio.h>

struct S
{
    const char *name;
    int size;
};    

static struct S gs;

static void func(struct S *s)
{
    gs = *s;
}

int main(void)
{
    {
        func(&(struct S){.name="foo",.size=20});
    }

    printf("name: %s size: %d\n", gs.name, gs.size);
    return 0;
}

I guess the string literal "foo" is not bound to the lifetime of the compound literal but rather resides in.rodata?我猜字符串文字“foo”没有绑定到复合文字的生命周期,而是驻留在.rodata 中?

Yes.是的。 That is correct.那是正确的。 In

 func(&(struct S){.name="foo",.size=20});

where "foo" initializes a pointer, it's almost as if you had written (if that could be written in C):其中"foo"初始化一个指针,就好像你已经写了(如果可以用 C 写的话):

 func(&(struct S){.name=(static const char[]){'f','o','o','\0'},.size=20});

(C doesn't technically allow static on compound literals, and C's string literals are really de-facto const-char-arrays, but their formal type is char[] without the const (for weird historical reasons)). (C 在技术上不允许static在复合文字上,并且 C 的字符串文字实际上是 const-char-arrays,但它们的形式类型是没有constchar[] (出于奇怪的历史原因))。

But be careful with it.但要小心。 In C, you can use string literals to initialize arrays, and if .name were an member array, then storing "it" (its decayed pointer) to a global variable would be ill-advised.在 C 中,您可以使用字符串文字来初始化 arrays,如果.name是一个成员数组,那么将“它”(它的衰减指针)存储到一个全局变量是不明智的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM