I'm trying to wrap my head around pointers in the C programming language, specifically the difference between two assignments: `A=&B;` and `*A=&B;`. I know both involve a pointer `A` and an integer `B`, but I'm confused about what each line actually does. Can someone explain in a straightforward way?
3 Answers
Makes sense when you break it down! Remember that with `*A`, you need to dereference it properly. If you just want to access `B`, `*A` gets you to `B` if `A` holds its address. So basically, `A=&B;` is setting `A` correctly, and you can then use `*A` whenever you need `B`'s value. Just don't mix them up like in `*A=&B;`!
Great question! When you use `A=&B;`, you're pointing `A` to the address of `B`. Both will refer to the same variable, so if you change `B`, it will reflect when accessed through `A`. On the other hand, `*A=&B;` is a bit misleading—you're trying to put the address of `B` into the value pointed to by `A`. It doesn’t really make sense. In simpler terms, think of it like having a piece of paper (A) with an address on it. You can write the address of a house (B) on the paper, but you can't put an address into the house itself, which is what the second line suggests!
Wow, that analogy really helps clarify things!
In your code snippet, you first have `int *A, B;`, which means `A` is a pointer to an integer and `B` is just an integer. When you do `A=&B;`, you're setting `A` to the address of `B`, meaning `A` now points to `B`. However, `*A=&B;` is a bit odd—you're trying to assign the address of `B` into the location that `A` points to, not `A` itself. That can lead to problems because you're treating that location like it's meant to hold a value (an integer), not another address. You typically want to use `*A=B;` if you want to set the value pointed by `A` to the value of `B`. Just be careful to assign it to the right thing!
That makes sense! So `*A=&B;` is kind of a misuse of pointers?

Exactly! If you're confused, just think about what you want each line to do.