c - C 中如何处理常量结构成员?

标签 c struct constants undefined-behavior bus-error

这样做可以吗?

struct MyStruct {
    int x;
    const char y; // notice the const
    unsigned short z;
};
struct MyStruct AStruct;
fread(&MyStruct, sizeof (MyStruct), 1,
      SomeFileThatWasDefinedEarlierButIsntIncludedInThisCodeSnippet);

我通过从文件写入整个结构来更改常量结构成员。那应该如何处理呢?如果一个或多个结构成员是常量,则写入非常量结构是否是未定义的行为?如果是这样,处理常量结构成员的公认做法是什么?

最佳答案

这是未定义的行为。

C11 草案 n1570 说:

6.7.3 Type qualifiers

...

...

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.

我对此的解释是:为了符合标准,您只能在对象创建(也称为初始化)期间设置 const 成员的值,例如:

struct MyStruct AStruct = {1, 'a', 2};  // Fine

正在做

AStruct.y = 'b';   // Error

应该给出编译器错误。

您可以使用如下代码欺骗编译器:

memcpy(&AStruct, &AnotherStruct, sizeof AStruct);

它可能在大多数系统上都能正常工作,但根据 C11 标准,它仍然是未定义的行为。

另请参阅memcpy with destination pointer to const data

关于c - C 中如何处理常量结构成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62464232/

相关文章:

go - 如何从接口(interface)中提取具体结构

c# - 查找类使用 enum、struct、public const 或其他东西?

C编程-角色 move 问题

c - 基础C题(初级)

c - for循环重写结构体C中数组的所有值

c++ - C 结构大小不一致

c++ - 如何制作一个深const指针

c# - C# 程序集中是否定义了 WM_KEYDOWN 常量?

c - 从 GUI 应用程序运行终端命令?

php - 如何在 Linux 中使用 C 编程检查我的 php 和 pear 版本?