doubt about new operator

1)int a = 100; -> allocates memory at compile time in stack

2) int *q = new int(100); -> allocates memory at run time in heap

With stmt1, we can directly use 'a' in the computations where as with stmt2, we have to use q indirectly to get the value 100 in computations.

What will be the difference if I use stmt2 in place of stmt1?




Statement 1 allocates space on the stack for a and assigns it value 100.

Statement 2 allocates space on the stack for q and assings it the value of the request for memory on the heap for an int that has been initialised with value 100.

q holds the value of the address (in the heap) where the int is reserved, or null if the allocation failed.

If you use q without dereferencing it, you'll the address. The compiler's type system should place some restrictions on the use of q and *q to help you identify incorrect usage.
Topic archived. No new replies allowed.