Pointers

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
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
You dereference with *
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 
@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.
Moschops wrote a good article on this subject. It is worth a read:
http://cplusplus.com/articles/EN3hAqkS/
Moschops and his chauvinistic view that every pointer is male! Peh!
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.



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.