Monday, February 2, 2009

tutorial 1 for pointers

hey C++ nerds and geeks!

we will be tackling pointers, the most evil of the eviloparisuis brothers, the curse of the black dragon, the swallower of black holes.

int x=5;

what does the above innocent, sweet and simple statement mean?!?

that x is an integer, which tells the computer to reserve 4 bytes and the starting address of those 4 bytes (i.e. the first byte is referred by &x). when we output x, we are actually outputting value at address &x. we will come back to this later. but, right now, let's get started with pointers.

int *p
you read this statement as "integer pointer p" or simply "p points to an integer"
this statement means that "p contains starting address of some integer"

we can output value of "that" integer that p points to with "*p" (read as pointer p)

now why is it important for a pointer to be associated with a data type such as integer?
because when we output *p, 4 bytes from starting address (p) are fetched, encoded as an integer and displayed. hence we cannot copy an integer pointer to a double pointer and so on.

pass 1:

int x=5; //assume address of x to be 0x112233
int *p; //p points to "some" address
p=&x; //means that p contains address of x, which means p=0x112233
cout<<*p< 5
*p=20; //modify value at address 0x112233 to 20
cout<< x<outputs 20

------------------------------------

pass 2:

int x=5; //assume address of x to be 0x112233
int *p; //p points to "some" address
*p=x; //modify value at "that" address to 5
cout<<*p<< endl; address =""> 5
*p=20; //modify value at "that" address to 20
cout<< x<< endl; //still outputs 5

------------------------------------

the above two versions had just one statement different

p=&x versus *p=x

p=&x means that p stores address of x, and therefore x changes if *p is modified and *p changes if x is modified. This is called "tight coupling"

*p=x refers to a one time copy. value at address stored in p takes the value of x but p DOES NOT point to x actually. Thus *p DOES NOT change if x changes and vice versa. This is called "loose coupling"

-----------------------------------

int x=10,y=20;
int *p,*q;
p=&x;
q=&y;
q=p;
x++;
cout<< *q<< " ";
*p=y;
cout<< *q<< endl;

what's the output of the above code?

a) 10 20
b) 11 11
c) 20 20
d) 11 20
e) 10 11

you got it right if you answered 'd'. you see, q=p means q now contains whatever address p contains, which is the address of x. hence both p.q point to x. when x increases to 11 (using x++)
*p and *q output 11. then *p=y means *p which is value at address inside p (which is the address of x) becomes y. Thus x becomes y (20). Thus *q (q still points to x) outputs 20.

No comments:

Post a Comment