Search code examples
cpointersstructconstants

C - Modifying data of a pointer inside a const struct


So I have been trying to learn C over holidays. Right now I came across const, so I have been playing around with it. After a while I came across this

#include <stdio.h>

typedef struct StructA {
    int* ptr;
} struct_a;

void modify(const struct_a value)
{
    *value.ptr = 0;
}

int main()
{
    int x = 5;
    const struct_a y = { .ptr = &x };
    printf("%d\n", x);
    modify(y);
    printf("%d", x);
    return 0;
}

// Output:
// 5
// 0

My general notion is that while the structure is constant, the value being pointer at is not, therefore you can modify it. Can someone explain what exactly is going on here?

Edit: Minor rephrasing


Solution

  • The function accepts its argument by value

    void modify(const struct_a value)
    {
        *value.ptr = 0;
    }
    

    You can imagine the function and its call the following way

    const struct_a y = { .ptr = &x };
    //...
    modify(y);
    //...
    
    void modify( /*const struct_a value*/)
    {
        const struct_a value = y;
        *value.ptr = 0;
    }
    

    It means that the data member ptr of the object value is constant.

    That is the structure within the function has in fact the following definition

    typedef struct StructA {
        int * const ptr;
    } struct_a;
    

    So you may not change the data member ptr itself (the value stored in the data member ptr). But you may change the object pointed to by the data member ptr

    *value.ptr = 0;
    

    As the pointer ptr in the function parameter and in the argument point to the same object you can change the object pointed to by the pointer of the structure declared in main

    Consider these declarations

    const int *ptr = &x;
    

    It means that the object pointed to by the pointer ptr is considered as a constant.

    In thsi declaration

    int * const ptr = &x;
    

    It is the pointer iyself that is a constant.

    And at last in this declaration

    const int * const ptr = &x;
    

    the both the pointer itself and the object pointed to by the pointer are constants.