1

Is there any difference between these two other than their duration?

int ptr; int *ptr = new int; 

I understand the concept of pointers but I don't see a much of a use for for delcaring an int with a pointer.

3
  • What should be declared with a pointer then, and why? Commented Jan 30, 2017 at 6:13
  • The way you use them would be different; the pointer one has to be used by *ptr. Commented Jan 30, 2017 at 6:13
  • 1
    One is on the stack, the latter is on the heap. You have to delete the one on the heap to not leak memory. Commented Jan 30, 2017 at 6:14

2 Answers 2

3

You use an object on the stack if you don't have the need for the object outside of the scope where it is created.

Example:

int foo(int in) { int i = in + 2; return i; } 

i is not needed outside foo. Hence, you create an object on the stack and return its value.

You use an object on the heap if you have a need for the object outside the scope where it is created.

int* foo(int in) { int* ip = new int(in + 2); return ip; } 

The pointer that ip points to is returned from foo and is expected to be used by the calling function. Hence, you need to create an object on the heap and return it.

That's the conceptual aspect of the difference. Normally, you won't need to use an object from the heap if you are talking about an int. The difference becomes important when you need to return an array.

int* foo() { int arr[] = {1, 2, 3, 4}; return arr; } 

That function will be a problem since it returns a pointer that will be invalid as soon as the function returns.

int* foo() { int* arr = new int[4]{1, 2, 3, 4}; return arr; } 

That will work since the returned pointer will point to valid objects even after the function returns. The calling function has to take responsibility to deallocate the memory though.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I understand it now.
-1

Difference can be seen from performance point of view.

Consider the worst case scenario:

int ptr; In this case all the required memory will be on the same page.

int *ptr = new int; In this case the address of ptr can be on one page and the memory which it points to can be on different page which may result in a page-fault while accessing the memory indirectly i.e *ptr.

2 Comments

Plz explain what's wrong in this.
(Not my vote) It's not wrong, just irrelevant, and rather misleading for beginners.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.