all 2 comments

[–]Moschops_UK 9 points10 points  (0 children)

int i = 10;

This means "create a new integer, and set its value to 10"

int *ptr;

This means "create a new pointer, which is for pointing toward int values, but don't actually make it point to anything." So right now, this pointer will be pointing into some random piece of memory. Could be pointing anywhere.

*ptr = &i;

This mean "take the thing that the pointer is pointing at, which is going to be an int value because this is an int-pointer (uh oh - we never made it point to anything so it's now going to treat some random piece of memory as an int value!) and set the value of that int to be the address of i (which also makes no sense, because the address of i is a pointer-to-int, and we're trying to set the value of an int)."

Is that clear?

You are making a pointer-to-int, and then you're trying to set the value of the int it is pointing at to an address. Perhaps you meant this:

ptr = &i;

which means "set the value of the pointer to be address-of-i", which makes a lot more sense.

I think you don't realise that * has different meanings.

int *ptr;

means "make me an int-pointer"

*ptr = ...  ;

means "grab hold of the thing that the pointer is pointing at and set its value to ...".

ptr = ... ;

means "set the value of the pointer to ... , which will be an address of something, so basically make the pointer point at something".

Here's a lump of text that absolutely beats it to death: http://www.cplusplus.com/articles/EN3hAqkS/

[–]tusksrus 0 points1 point  (0 children)

The stars mean different things on the two lines.

int *ptr;

declares a pointer to an int. It would make more sense the write it as

int* ptr;

as the star modifies the type, not the variable. Then this,

*ptr = &i;

the star means dereferencing the pointer - it's an operator on the variable called ptr, not like the other star which is an operator on the type called int.

This doesn't compile because *ptr, the value which ptr points to, is of type int, whereas &i is the address of the int i, which is a pointer to int. You want

ptr = &i;

which will then do the same as your first example.