Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign integer value to heap

Tags:

c++

  #include<iostream>
  using namespace std;
  int main() 
  { 
    int i= new int;
    cout<<i;
    return 0;
  }

when i tried to assign int i value to heap it shows error: invalid conversion from 'int*' to 'int'

when i assign value to int pointer then it assign to it.why we cannot assign value to int to heap.Yes i know as much as possible avoid assigning value to heap. I looked many stackoverflow post everyone explained about int *p=new int[10]; Please someone explain this to me. Thanks for your help.

like image 494
InvI Avatar asked Jan 30 '16 16:01

InvI


People also ask

Is int stored in heap?

Now, the values present in heap may be cleared by Garbage collector. However, we can say normal variables like int, Boolean, double float are stored on stack and objects are stored on Heap.

Is Int a stored in heap Java?

For example, int a = 55 will literally put the value 55 into that space. However, if the type is non primitive, that is some subclass of Object, then the value put onto the stack is actually a memory address. This memory address points to a place on the heap, which is where the actual Object is stored.

How do I allocate an array in heap?

Creating an array in the heap allocates a new array of 25 ints and stores a pointer to the first one into variable A. double* B = new double[n]; allocates an array of 50 doubles. To allocate an array, use square brackets around the size.

What is new int in C++?

*new int means "allocate memory for an int , resulting in a pointer to that memory, then dereference the pointer, yielding the (uninitialized) int itself".


2 Answers

new int returns a pointer to int, that is, int*. Assigning it to an int is an obvious type mismatch.

The pointer returned by new T points to a memory location on the heap a.k.a. free store, which provides enough space to store one object of type T. T is an arbitrary type here.

Your code could be altered to this:

int* ptr = new int;
*ptr = 1;
cout << *ptr;    // prints 1

Don't forget to delete afterwards!


Note that the heap should only be used for dynamic data used beyond scope boundaries. In your case, it's way too heavyweight. Just use a good old automatic variable:

int i = 1;
like image 93
cadaniluk Avatar answered Sep 29 '22 19:09

cadaniluk


new int;

allocates memory for a single int, initializes one int in there, and gives you a pointer to that. It doesn't give you an int but a pointer to int, hence int*.

You probably just want to do

int i = 42;

or so.

EDIT:

You can of course also do

int* i = new int;

but the way you use it, you shouldn't do that. Memory gotten via new stays allocated until you delete it; that means that you'd code a memory leak if you used new without delete.

like image 24
Marcus Müller Avatar answered Sep 29 '22 19:09

Marcus Müller