C++ cout giving unexpected with dereferenced pointer
<p>So, I have a function which returns a pointer to a dynamically allocated double, and I need to print the value to which it points (silly I know).</p>

<pre><code>double * ans1p = dot(v1, v2);
    double ans1 = *ans1p;
    cout &lt;&lt; "Answer to problem 1:" &lt;&lt; endl;
    cout &lt;&lt; ans1 &lt;&lt; endl;
    cout &lt;&lt; *ans1p &lt;&lt; endl;
</code></pre>

<p>The first cout statement returns the expected value.</p>

<p>The second returns something random and unexpected. What's the difference? It seems to be that in both cases what's being printed is the value pointed to by ans1p.</p>

<p>I'd rather eliminate ans1 and its cout statement entirely.</p>

<p>OK, here is the dot function:</p>

<pre><code>double * dot(Vector &amp;v1, Vector &amp;v2) {
if (getLength(v1) != getLength(v2) ) {
    std::cout &lt;&lt; "Error: cannot perform dot product. Vectors must be " &lt;&lt;
        "equal length." &lt;&lt; std::endl;
    return 0;
}
double result = 0;
for (unsigned int i = 1; i &lt;= getLength(v1); ++i) {
    result += (v1.elements[i] * v2.elements[i]);
}
double * resultPtr = new double;
resultPtr = &amp;result;
return resultPtr;
}
</code></pre>

<p>For the record, I wouldn't attempt to do it this way, but it's part of an assignment. And I'm supposed to return the 0 pointer in the event of mismatched sizes.</p>

<p>OK, looking at it, I can see that result is out of scope when the function returns, and the pointer I'm returning just points there (right?). But then, I can't think of how to do what I want to do. </p>

<p>I suppose I could declare a double pointer outside the function, pass the pointer as an argument, and set it inside the function. But I'd kind of like to figure out how to do it the way I planned. Although, thinking about it, it might be better to do it this way once I understand what's going on with the old way, right?</p>
