将字符串分配给常量结构

时间:2018-02-19 16:37:37

标签: 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'限定符#34;

我意识到当我将它作为const结构时,我不应该尝试分配结构的值,但我也不能将stringcpy放在结构中。有什么办法可以在c?

中将字符串赋值给const结构的元素

1 个答案:

答案 0 :(得分:6)

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

您可以删除限定符,也可以像这样初始化struct

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

这会将"some_string"中以空值终止的字符序列放入word[100]数组的初始部分,并用'\0'个字符填充其余部分。

相关问题