0

Hey guys i seem to be having an issue with the following code:

// show solution to variable scope problem using "the heap"
// a block of memory controlled by the programmer
#include<iostream>
using namespace std;

double* Function()
{
        double* dLocalVar = new double;
        return dLocalVar; // give address of dLocalVar to calling function
        }

int main(void)
{
    double* pdLocal; // pointer to double type variable
    
    pdLocal = Function(); // targeted address is return val of Function(), 
    // which is a pointer to memory address of local var in another function
    
    *pdLocal = 5.5; // assign 5.5 to targeted address

    cout << "*pdLocal = " << *pdLocal;

    // return memory to the heap
    delete pdLocal;
    // set target memory location to 0
    pdLocal = 0;
    
    cin.get();
    return 0;
}

The Program seems to compile however i am unsure about the underlying processes at work in this program. When the variable is declared

double* dLocalVar = new double;

why is the variable new double not defined?

Any help much apreciated :)

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by 2bit
0

"new double" is not a variable. "new" is a c++ operator that allocates memory from the heap, and "double" is the type of memory that new will allocate.

0

"new double" is not a variable. "new" is a c++ operator that allocates memory from the heap, and "double" is the type of memory that new will allocate.

Thanks, i see what you mean :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.