pointer decleration

Greetings,

I'm wondering about how to declacre my stuff.
on my journey into c++, the internet has shown me theese:

1
2
3
4
SomeType type;
SomeType* type;
SomeType *type;
SomeType** type;

Especially 2 and 3 freak me out. Could someone explain this to me? what do each of theese declerations mean and what does it mean for cleaning up theese types?
Last edited on
They are the same (Pointer to SomeType)
I wonder how doesn't 4 freak you out, since it's a Pointer to Pointer to SomeType.


Think of a chocolate bar.
1
2
3
// Say this chocolate bar is made of 8 pieces
ChocolatePiece A[8];
ChocolatePiece* B;



Your chocolate bar looks like this:
[ ][ ][ ][ ][ ][ ][ ][ ]
This is what A looks like right now.


Now, look at your finger.
Make it point at one piece of your chocolate bar.
[ ][ ][X][ ][ ][ ][ ][ ]
1
2
 // Take the address ("location", "position") of A's third item
B = &A[3];

This is what B is meant for: Pointing to an item.

Your finger can touch (read) what it's pointing at:
1
2
// The same as myFingerPointsTo = A[3];
ChocolatePiece myFingerPointsTo = *B;

Also your finger can smash (change) what it's pointing at:
1
2
// Now A[3] is WhiteChocolate.
*B = WhiteChocolate;

A pointer to a pointer... is just like a finger, pointing to a finger, pointing to a chocolate piece.


The only "unusual" tokens you'll have to remember with pointers are * and & .

When declaring a type, using * means this type is a pointer:
int* a; // a is a pointer-to-int
When declaring a type, using & means this type is a reference:
int& b = c; // a is a reference-to-int. Must be initialized.
When using variables, using * means you want to read what a pointer is pointing to.
int d = *a;
When using variables, using & means you want to get a pointer to this item.
int* e = &d;

References are slightly different pointers. You can think of them as variable aliases.
1
2
3
int a=0;
int& b=a;
// a and b are the same. Only their name differs. 
Last edited on
Thank you. this helps. Still a bit confused about this stuff, but i'm getting there.
Last edited on
Topic archived. No new replies allowed.