简体   繁体   English

尽管 const 限定符声明,为什么嵌套结构成员会改变?

[英]Why nested structure member get alter despite const qualifier declaration?

I observed nested structure member get alter despite my const qualifier declaration, may I know any method for me to avoid nested structure member get alter inside the function?尽管我声明了const限定符,但我观察到嵌套结构成员得到改变,我可以知道任何方法来避免嵌套结构成员在函数内部得到改变吗?

Code代码

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

struct middle_data
{
    struct base_data *int_data_ptr;
};

struct base_data
{
    int value;
};

void function( const struct  middle_data const *middle_ptr)
{

    middle_ptr->int_data_ptr->value= 2; // how to forbid value get alter?

    struct base_data *ptr= middle_ptr->int_data_ptr;

    printf("ptr->value = %d\n",  ptr->value);
}

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

   struct  middle_data *middle_data_ptr;

    middle_data_ptr = (struct  middle_data*)malloc(sizeof(*(middle_data_ptr)));

    middle_data_ptr->int_data_ptr =malloc(sizeof(*(middle_data_ptr->int_data_ptr)));

    middle_data_ptr->int_data_ptr->value=3;

    function(middle_data_ptr);

    printf("  middle_data_ptr->int_data_ptr->value = %d\n",    middle_data_ptr->int_data_ptr->value);

    free(middle_data_ptr);
    free(middle_data_ptr->int_data_ptr);
    return 0;
}

唯一的方法是将 struct base_data的成员设为const

For starters in this function declaration对于此函数声明中的初学者

void function( const struct  middle_data const *middle_ptr)

one qualifier const is redundant.一个限定符const是多余的。 They both mean that the pointed object is constant not the pointer itself.它们都意味着指向的对象是常量而不是指针本身。

So this qualifier const means that data members of the pointed object are also constant that is in fact you have所以这个限定符const意味着指向对象的数据成员也是常量,实际上你有

struct base_data * const int_data_ptr;

That is you have a constant pointer that points to a non-constant object that may be changed.也就是说,您有一个常量指针,指向一个可以更改的非常量对象。

If you do not want that the pointed object would be changed then you have to declare the structure like如果你不想改变指向的对象,那么你必须声明这样的结构

struct middle_data
{
    const struct base_data *int_data_ptr;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM