Zasito
Zasito

Reputation: 279

Pointers in C++ difference

Let's suppose this code:

int a;
int * point;
a = 5;

point = &a; // <-----

The line I'm arrowing is the same as...

*point = a;

... or is there a difference in it?

Upvotes: 0

Views: 99

Answers (6)

user2568508
user2568508

Reputation:

Actually, this

*point = a;

may crash, because you haven't allocated a memory to which point would be pointing. It's also not pointing to say a stack variable- in which case it would change value of that stack variable to a.

In other words, point is not pointing to anything, and you are trying to set value of that non existing 'object'.

Upvotes: 0

Jamin Grey
Jamin Grey

Reputation: 10495

  • point = &a; makes 'point' point to 'a'.
  • *point = a; assigns the value of 'a' to whatever 'point' is already pointing to.

'point' holds an address. '&' gets an address from a variable. point = &a; gets the address of 'a', and assigns it to the pointer.

'*' deferences a pointer (getting the variable it points to), so *point = a assigns the value of 'a' to the dereferenced pointer - that is, whatever variable's address was already stored in the pointer.

Upvotes: 3

utnapistim
utnapistim

Reputation: 27385

The first line assigns the address of a (&a) to pointer.

The second line assigns the value of a to the memory block pointed to, by pointer (*pointer).

To note: If the pointer doesn't point to the address of a variable in scope, or to an address dynamically allocated, you cause a memory corruption in the second case.

Upvotes: 0

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158629

No, they are not the same this:

*point = a;

requires that point already points to valid memory in your current program it would not and therefore would be undefined behavior. while this line:

point = &a;

will assign to point the address of an existing object.

Upvotes: 0

Paul Roub
Paul Roub

Reputation: 36458

Completely different.

point = &a;

means "point now contains the address of a".

*point = a;

means "the (currently undefined) area of memory that point points to now contains the value of a". That version is likely to crash.

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 191058

The difference is that you are dereferencing point which may have an invalid address at that point. It would not actually write the value to the location point has.

Upvotes: 0

Related Questions