gpt4 book ai didi

忽略 Const 限定符

转载 作者:行者123 更新时间:2023-12-01 23:57:08 32 4
gpt4 key购买 nike

<分区>

我有一个结构体 type_s。然后我将指向 struct type_s 的指针定义为类型。

如果我有一个 const struct type_s*,那么如果对 struct 成员进行赋值,编译器将正确地报错,如函数 Test1() 中所示。但是如果我创建一个 const 类型,它是相同结构指针的 typedef,编译器将不会提示和编译,函数 Test2()。

typedef struct type_s* type ;
struct type_s
{
int a ;
} ;

void Test1( const struct type_s* t )
{
t->a = 123 ; //complains, ok
}

void Test2( const type t )
{
t->a = 123 ; //doesn't, it should in my oppinion
}

对我来说,它们在逻辑上是同一回事。我错过了什么?

是为指向该结构的常量指针创建另一个 typedef 的唯一解决方案,如下所示:

typedef const struct type_s* ctype ;

它将像在 Test1() 中一样正常工作。

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