Pointers

Feb 23, 2012 at 3:11pm
Hello,

I watched the tutorial about pointers, I have a little problem.
I do not really understand their works and utility.

Can you explain more precisely the works and utility of a pointer ?

Last edited on Mar 1, 2012 at 12:25pm
Feb 23, 2012 at 4:06pm
I had trouble with pointers at first too. I like to think of it as an apartment building-

A pointer is like the address (for example, apartment 314). This address is IN the memory of your computer, it never changes. Now, say you make a variable declared as
int x=0;
but you need to know where in memory that's stored. The way you would find this is by setting your pointer

int *addressofx=x

Now addressofx POINTs to x. It tells you where x is actually located, so that you could access it for operations. This is really not that useful as you begin, but once you get into complex functions and object oriented programming it will become invaluable. using pointers, you can send a function a variable that is local (confined to only one small portion of your code) by sending it's address, so that other functions can edit that value.

I'm sure you've also heard about the dereference operator (&). This is used to find the VALUE at an address in memory. For example, as of right now, our pointer addressofx is 314. It's the value in memory where x is stored. If you wanted to know the value of x, you'd say

std::cout << &addressofx << endl;

hope this helped!
Last edited on Feb 23, 2012 at 4:06pm
Feb 23, 2012 at 4:10pm
You dereference with *
Feb 23, 2012 at 4:22pm
Yeah & is the reference operator and * is the indirection operator

1
2
3
4
int x = 10; // integer variable
int *y; // pointer-to-integer variable
y = &x; // y now points to the address of x
*y = 11; // y (therefore x) now has a value of 11 
Feb 23, 2012 at 4:39pm
@Texan40:
*y = 11; // y (therefore x) now has a value of 11
No, no, no. I know it's probably a typo, but *y (thus x) now has a value of 11, not y.
Feb 23, 2012 at 4:47pm
Moschops wrote a good article on this subject. It is worth a read:
http://cplusplus.com/articles/EN3hAqkS/
Feb 23, 2012 at 4:57pm
Moschops and his chauvinistic view that every pointer is male! Peh!
Feb 23, 2012 at 7:00pm
Thanks for the example to the apartments, it's easier to understand like this.

I'll read the article tonight and if I have questions tomorrow, I know or posted.



Mar 2, 2012 at 3:01pm
LOL my mistake with the * and the &. The rest of what I said is right I think, but Texan40 and ciphermagi are right there. Sorry for the mixup.
Topic archived. No new replies allowed.