What is the diference btw a pointer & a pointer variable?
I mean I was confused by the following statement while reading an article,
int x, y;
*yPtr = 7;
yPtr =&y;
*yptr and yPtr is confusing.
Printable View
What is the diference btw a pointer & a pointer variable?
I mean I was confused by the following statement while reading an article,
int x, y;
*yPtr = 7;
yPtr =&y;
*yptr and yPtr is confusing.
basically, instead of storing a value, a pointer stores an adress to a variable that stores a value.
Here you set the value yPtr points at
*yPtr = ...
Here you set the adress to where yPtr should point. You should not use an arbitrary number here but rather get the address of a variable through the & operator ( &myInt ).
yPtr = ...
There is a pointer tutorial on this site:
http://www.cprogramming.com/tutorial/lesson6.html
As Magos said, pointers store an address to a variable.
In your examples:
yPtr =&y;
store the address of y into yPtr.
You can now reference y or *yPtr as the same value.
*yPtr = 7;
7 is stored in the location that yPtr points to. IOW y is set to 7.
By the way, you must specify yPtr:
int x, y, *yPtr;
This tells the compiler that yPtr will store an address.
But, pointers are used alot, so you'll get plenty of practice. :)
One thing that confused me at first was that the asterisk (*) has a different meaning in a declaration than in an assignment:
int *yPtr = &y; // This is OK (* means yPtr is a pointer, not dereferenced)
*yPtr = &y; // Wrong (Address of y assigned to whatever yPtr "points to")
yPtr = &y; // This is OK (Address of y assigned to yPtr)
*yPtr = x; // This is OK (* means "dereference". x is assigned to whatever yPtr "points to")
I always found it easier to think about it like this:now when you print it out, it looks liek this:Code:...
int x=10; //integer x
int y=10; //integer y
int*xptr=new int; //pointer to new integer
int*yptr=&y; //pointer to new integer (same as yptr=&y)
...
*xptr+=5; //add 5 to xptr's copy of x (xptr only points to the value)
*yptr+=5; //add 5 to y (yptr points to the address of y)
...
delete xptr; //because it points to a newly allocated int-size chunk of memory
*xptr=0; //point it to nothing
...
it's like in a function, when you use the ampersand (&) in the calling of the function to change that variables value in main as well... actually, that's exactly what it is, but I don't want to try to confuse you anymore...Code:x: 10
y: 15
*xptr: 15
*yptr: 15
xptr: 0x...
yptr: 0x...
thanku v m.