user1247347
user1247347

Reputation: 201

What is the difference between these uses of pointers?

int *p1=10;

and

int *p2;
p2=new int;
*p2=10;

What is the difference between these two variables? Aren't both the variable allocated in the heap?

Upvotes: 1

Views: 554

Answers (4)

Emilio Garavaglia
Emilio Garavaglia

Reputation: 20730

The expression int* p1 = 10 should not compile: it initializes a pointer with an integer!

Upvotes: 0

user1192525
user1192525

Reputation: 677

Both p1 and p2 are pointers to integer variables.

The initialization of p1 is wrong. As a pointer it should contain the address of an integer variable. And you are assigning the "address" a value of '10': you are setting it to point to address 0x0000000A, which is almost certainly invalid.

Upvotes: 0

Danica
Danica

Reputation: 28846

The difference is that the first one doesn't compile:

lol.cpp:2:10: error: cannot initialize a variable of type 'int *' with an rvalue of type 'int'
    int *p1 = 10;
         ^    ~~
1 error generated.

whereas the second one makes an int on the heap with value 10, and allocates a pointer to that value on the stack.

If the first one did compile, say if you added a cast, it'd be assigning the value 10 to the pointer p1, meaning that p1 would point to the memory address 10 = 0x0A, and *p1 would try to dereference that address as an int, which would be a segfault. (If you used a different number that happened to land within your process's memory space, it'd be some arbitrary integer based on what the contents of the memory contained.)

Upvotes: 4

mip
mip

Reputation: 8713

And according to another part of your question. No, they are not both allocated on the heap. In fact they are both allocated on the stack. Only the second one points to a region allocated on the heap by new operator. They would be allocated on the heap, if they were part of an object being allcated with new.

Upvotes: 1

Related Questions