gpt4 book ai didi

c - 复合文字中的字符串文字

转载 作者:行者123 更新时间:2023-12-05 02:25:30 24 4
gpt4 key购买 nike

我对复合文字中的字符串文字有疑问。

由于 struct S 复合文字的生命周期在 func 调用周围的 block 内,我想知道在全局 gs 变量内使用名称指针是否仍然可以。我猜字符串文字“foo”未绑定(bind)到复合文字的生命周期,而是驻留在 .rodata 中?那正确吗?至少 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?

是的。那是对的。在

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

其中 "foo" 初始化一个指针,这几乎就像您已经编写了(如果可以用 C 编写的话):

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

(C 在技术上不允许对复合文字使用 static,并且 C 的字符串文字实际上是 const-char-arrays,但它们的形式类型是 char[] 没有 const(出于奇怪的历史原因))。

但要小心。在 C 中,您可以使用字符串文字来初始化数组,如果 .name 是一个成员数组,那么将“它”(它的衰减指针)存储到一个全局变量是不明智的。

关于c - 复合文字中的字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74565905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com