b1000
b1000

Reputation: 107

Modifying a const pointer in C

I am trying to understand why the following code compiles and runs fine. I would expect any assignment using data inside f not to compile with a gcc error assignment of member ‘i’ in read-only object. Is there some kind of exception, because data.i is allocated dynamically?

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

struct a {
    int *i;
};

void f(const struct a *data) {
    data->i[0] = 55; 
}

int main() {
    struct a data;
    data.i = malloc(2 * sizeof(int));
    
    f(&data);
    
    printf("%d\n", data.i[0]);
    
    return 0;
}

Upvotes: 3

Views: 447

Answers (3)

0___________
0___________

Reputation: 67476

You cant modify i but you can modify the objects referenced by i.

To prevent it you need to:

struct a {
    const int *i;
};

Upvotes: 0

Lundin
Lundin

Reputation: 213809

const front of a struct will make it read-only. If the struct contains pointer members, then those pointers themselves will turn read-only. Not what they point at.

That is, const struct a will make the member i behave is if it was declared as int *const i;, meaning that the pointer itself cannot be changed to point elsewhere. The pointed-at data is still of read/write int though.

If you want to restrict access to i inside a function, you should make that function take a const int* parameter and pass the i member to that function.

Upvotes: 3

chux
chux

Reputation: 153457

In the below code, const indicates what data points to is not to be modified. data->i[0] = 55; does not modify the pointer data->i. Instead that line of code modifies the memory pointed to by data->i. This is allowed as pointer .i is int * and not const int *.

struct a {
    int *i;
};

void f(const struct a *data) {
    data->i[0] = 55; 
}

Upvotes: 1

Related Questions