Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading