3 回答

TA贡献1831条经验 获得超10个赞
注意
typedef int* intptr;
const intptr x;
与以下内容不同:
const int* x;
intptr是指向int的指针。const intptr是指向常量的指针int,而不是指向常量的指针int。
所以,在typedef指针之后,我不能再将其常量化为内容了吗?
有一些丑陋的方法,例如gcc的typeof宏:
typedef int* intptr;
intptr dummy;
const typeof(*dummy) *x;
但是,如您所见,知道后面的类型是没有意义的intptr。

TA贡献1909条经验 获得超7个赞
虽然以上答案已经解决了问题,但我确实想念为什么...
因此,也许是一个经验法则:
将const总是指它的前身令牌。
如果没有这种情况,它是“ consting”它是后继令牌。
该规则确实可以帮助您声明一个指向const指针的指针或类似的东西。
无论如何,考虑到这一点,应该弄清楚为什么
struct Person *const person = NULL;
声明一个指向可变结构的const指针。
考虑一下,您的typedef 使用指针标记将“分组”。所以,写struct Person*
const PersonRef person = NULL;
您的编译器会看到以下内容(伪代码):
const [struct Person *]person = NULL;
由于的内容已不const剩,因此它将令牌标记为正确的struct Person *常量。
好吧,我认为,这就是为什么我不喜欢使用typedef隐藏指针的原因,而我确实喜欢typedef。那写作呢
typedef struct Person { ... } Person;
const Person *person; /*< const person */
Person *const pointer; /*< const pointer to mutable person */
对于编译器和人员来说,您应该做什么很清楚。

TA贡献1853条经验 获得超9个赞
永远不要将指针隐藏在typedef后面,这确实是一种糟糕的做法,只会造成bug。
此类臭名昭著的错误是,声明为const的typedef:ed指针类型将被视为“指向非常量数据的常量指针”,而不是“直观地希望指向常量数据的非常量指针”。 。这就是程序中发生的情况。
解:
typedef struct
{
int age;
} Person;
const Person* person = NULL; // non-constant pointer to constant Person
添加回答
举报