Pointer to a const structure, can members still be modified?

  • A+
Category:Languages

I have a structure which I want to pass to some external c code via some callback function that they register with my program. However, I want to pass that structure as read-only. My concern is that they can still modify the structures which I have pointer to inside the original structure that I pass. Explained with small example below:

struct s1 {     int a;     int b; };  struct s2 {     int x;     struct s1 *y; };  void f(const struct s2 *o) {     //o->x=10; //error     o->y->a=20; //no error     o->y->b=30; //no error }  int main() {     struct s1 o1 = {10, 20};     struct s2 o2 = {30, &o1};     f(&o2); } 

So, How do I improve my code design so that they cannot modify anything w.r.t the structure I pass?

 


You cannot. Even if you pass the struct s2 by value, you will get in the function a pointer to a non const struct s1, simply because it is what s2 contains per its definition.

And once you have a pointer to a non const object you can change that object. What I mean here and what other answers mean, is that it is not a language problem - more exactly the language can nothing for you here - but a design problem. If for any reason it is not acceptable that the struct s1 can be changed from f then you have to find a different design where you do not pass a non const pointer to it, be it member of a const struct or not. Here a simple way would be to pass the individual members:

void f(int x, const struct s1 *y) {     y->a = 20;  // error } 

It may not be what you expect, but it is the best I can say for C language.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: