c - 将字符串分配给常量结构

标签 c string struct

我有以下结构,

struct example_struct { 
     int number ;
     char word[100] 
}

我在代码中将其初始化为常量结构

const struct example_struct example {
    .number = 5
} ;
strcpy(example.word, "some_string") ;

当我尝试编译我的代码时,它会给我警告:

“警告:传递‘strcpy’的参数 1 会丢弃来自指针目标类型的‘const’限定符”

我意识到,当我将结构设为 const 结构时,我不应该尝试为其赋值,但我也不能将 stringcpy 放入结构中。有什么方法可以将字符串分配给 c 中的 const 结构的元素?

最佳答案

警告是正确的 - 由于您使用 const` 限定符声明了您的 struct,因此在运行时将数据复制到其中是未定义的行为。

您可以删除限定符,或者像这样初始化您的struct:

const struct example_struct example = {
    .number = 5
,   .word = "some_string"
};

这会将来自 "some_string" 的以 null 结尾的字符序列放入 word[100] 数组的初始部分,并用'\0' 个字符。

关于c - 将字符串分配给常量结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48870447/

相关文章:

包含字符串数组的结构的 C# dllimport

pointers - 遍历一片结构并更新值

c - 在单写入多读取系统中我们需要锁吗?

c - 在 C 中隐藏结构定义是一种好习惯吗?

c - 尝试抓取 C 中空格后的字符

regex - 在参数 bash 中查找并替换字符串

c - 在c中使用bash进入文件夹

c - 仅删除句子中的字母字符

javascript - 在 JavaScript 中替换 4 个“字符之间的字符串中的字符串片段

c - "Dereferencing pointer to incomplete type", typedefs 没问题