what understand right is.
int = 100; int *a_ptr; // creates pointer variable named a_ptr , points type int a_ptr = &a; // a_ptr address of *a_ptr = 5; // value of pointer = value of set 5.
what dont understand point of pointers occupy address of variable right value or content isnt it?
if *a_ptr
value shouldn't *a_ptr = &a;
?
thanks
think of pointer road sign: tells can find something. nothing more, nothing less. value/reason pointers exist because it's concept we're familiar with. c passes value. let's use far-fetched analogy that, believe, clear couple of things you:
imagine having been on holiday , telling hotel stayed in. instead of describing in great detail, you'd give other person name, address, , perhaps more details find place. not set describing entire thing in detail, nor tear hotel down , take you, let alone rebuild every time tell it.
back c: c passes value. in analogy, handing 1-to-1 scale replica of hotel you're raving on about. that's expensive, time consuming , quite annoying. people you've given copy of hotel can change it, you'd never know: there's common starting point (the original hotel), every copy independent of 1 after that.
like in real life, you'd write address of hotel down , give out family , friends. that's c pointers: tells can find (a struct hotel
or int
), , others can use address travel it.
added benefit being if of friends pay visit place, can tell it's changed in ways: colour green, not blue, owners have changed, etc...
using address allows has address have access up-to-date information place.
if hotel closes down, address become pointless, of course, if uses address gave them thinking they're going stay in great place, they'll angry. happens next hard predict (undefined behaviour).
so in resuming:
int x = 123;// hotel int *x_address = &x;//an address hotel int *for_friend = &x; int *friend2 = &x; // can hand out sever addresses same hotel *x_address += 1; // read *(travel to)x_address arrive @ hotel x, , stay += 1 night or //friend2 wants see how many nights spent in hotel x: printf("%d\n", *friend2);//124 -> 123 originaly + *x_address += 1
if x
goes out of scope, that's equivalent of hotel closing. if sombody *x_address
(travels x), behaviour undefined.
i've used different analogies in past explain in way can @ pointers make them easier understand, i've written while back, don't know if makes things clearer, thought i'd post link here:
Comments
Post a Comment