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 :)

Recommended Answers

All 2 Replies

"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.

"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 :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.