gpt4 book ai didi

您能否安全地将具有非 const 成员的 C 结构转换为具有 const 成员的等效结构?

转载 作者:太空宇宙 更新时间:2023-11-04 06:50:17 24 4
gpt4 key购买 nike

当一个结构具有非常量成员而另一个具有常量成员时,从一种结构转换为另一种结构(两者具有相同的形状)是否安全?该代码演示了我正在尝试做的事情..

#include <stdio.h>
#include <stdlib.h>

struct nonConst {
int value;
struct nonConst * next;
};

struct Const {
const int value;
struct nonConst * const next;
};

int main (int argc, char ** argv) {

struct nonConst * nc = (struct nonConst*)malloc(sizeof(struct nonConst));
nc->next = NULL;
nc->value = 8888;

struct Const * c = (struct Const*)nc;/*cast the non-const members to const members*/

fprintf(stdout, "%d\n", c->value);


return 0;
}

以上是否安全(或在某些情况下是安全的)或者我会遇到问题吗?

最佳答案

这属于标准未明确涵盖的领域。首先,没有类型的内存由malloc分配。

写入动态分配的空间设置内存的有效类型。但该标准并未说明 nc->value 是否“印记”了整个 struct nonConst ,或者它是否只是写入了一个 int。同样,它也没有说明 fprintf(stdout, "%d\n", c->value); 是否要求存在整个有效的 struct Const,或者它是否只是读取 const int

这种区别很重要,因为可以从同一内存位置写入一个 int 并读取一个 const int(严格的别名规则特别提到了这一点)。


一些主要的编译器采取的立场是 nc->valuec->value 印记/需要整个结构,而不仅仅是涉及的成员。因此,实际上,我认为使用此代码并不安全。

我在 this answer 的第二部分详细介绍了该主题.

关于您能否安全地将具有非 const 成员的 C 结构转换为具有 const 成员的等效结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52546353/

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