首页 文章

const限定符被忽略[重复]

提问于
浏览
3

这个问题在这里已有答案:

我有一个struct type_s . 然后我输入一个指向结构type_s的指针作为类型 .

如果我有 const struct type_s* 那么编译器将正确地抱怨如果对结构成员进行了赋值,如函数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()中正常工作 .

2 回答

  • 1

    你缺少的是const指针与指向const对象的指针不同 . 你有一个 . const指针是一个指针,其存储的地址不可修改;指向const的指针是一个不能用于修改其指示对象的指针 .

  • 2

    它们不是同一件事 . const 在应用于指针变量和非指针变量的定义或声明时具有不同的语义 .

    const struct type_s *t
    

    上面的语句将 t 定义为指向 const struct type_s 类型的对象的指针 . 这里, const 限定对象 t 指向的类型 struct type_s ,而不是指针 t .

    typedef struct type_s *type ;
    

    上面的语句为类型 struct type_s * 定义名为 type 的别名 .

    const type t;
    // equivalent to
    type const t;
    // equivalent to
    struct type_s *const t;
    

    上面的语句将 t 定义为 type 类型的常量对象 . 这里 const 限定了对象 . 您不能将 typedef 替换为其原始类型,并将其重新解释为它是一个宏 . 指针信息嵌入在 typedef 中,它将被视为非指针类型 .

相关问题