gpt4 book ai didi

c - typedef 指针常量怪异

转载 作者:行者123 更新时间:2023-11-30 16:23:10 24 4
gpt4 key购买 nike

请考虑以下代码:

typedef struct Person* PersonRef;
struct Person {
int age;
};

const PersonRef person = NULL;

void changePerson(PersonRef newPerson) {
person = newPerson;
}

出于某种原因,编译器提示只读值不可分配。但是const关键字不应该使指针成为const。有什么想法吗?

最佳答案

请注意

typedef int* intptr;
const intptr x;

不等于:

const int* x;

intptr 是指向 int 的指针。 const intptr 是指向 int 的常量指针,而不是指向常量 int 的指针。

so, after a typedef pointer, i can't make it const to the content anymore?

有一些丑陋的方式,比如gcc的typeof macro :

typedef int* intptr;
intptr dummy;
const typeof(*dummy) *x;

但是,如您所见,如果您知道 intptr 背后的类型,那是毫无意义的。

关于c - typedef 指针常量怪异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54102297/

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