I am trying to alter a pointer member (cI of a) within a structure (custInt) via another pointer (b). I am not sure why a is not changing despite the fact that b was set equal to a. Do a and b not point to the same memory address? If not, how could I make them point to the exact same thing and both change when either one changes?

Here is my code: https://gist.github.com/McHippy3/3ed5ed4b5f310aa3635eb4d6a97c949d

1 Answer 1

    custInt *b = a -> cI;
    b = malloc(sizeof(custInt));

First line initialises b to a -> cI. Second line discards that value to replace it with the address returned by malloc. To assign to both, you could do

    custInt *b;
    b = a -> cI = malloc(sizeof(custInt));

= assignment expression has the value that's assigned, and is evaluated right to left. Same for combined assign like +=.

  • Ohhhhhhhhh, that makes sense, thank you
    – David Wu
    Jan 10, 2019 at 23:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .