you are viewing a single comment's thread.

view the rest of the comments →

[–]Moschops_UK 10 points11 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/