Note that there are some explanatory texts on larger screens.

plurals
  1. POOddity with structs defined in files other than main.cpp
    text
    copied!<p>I have found that a struct (with an array of doubles and one integer) defined in a separate Cpp-file, but called from main sends unreasonable values to cout for the array. Below what I hope to be a minimum example, along with the console output.</p> <p>My apologies should my code be scrambled -- I have been struggling a bit with formatting it properly.</p> <p>I'd be grateful if someone could help me understand and rectify this.</p> <p>Best, Jo</p> <p><strong>(1) main.cpp:</strong></p> <pre><code>#include "iostream" #include "defs.h" using namespace std; int main() { MyStruct myModel=ConstructModel(); cout &lt;&lt; endl &lt;&lt; "myModel goes first:" &lt;&lt; endl; for(int i=0; i&lt;myModel.n; i++) cout &lt;&lt; "myModel.Y[" &lt;&lt; i &lt;&lt; "]=" &lt;&lt; myModel.Y[i] &lt;&lt; endl; cout &lt;&lt; "myModel.n=" &lt;&lt; myModel.n &lt;&lt; endl; MyStruct myOtherModel; myOtherModel.n=2; double Y[2]={0.1,0.1}; myOtherModel.Y=Y; cout &lt;&lt; endl &lt;&lt; "now myOtherModel:" &lt;&lt; endl; for(int i=0; i&lt;myModel.n; i++) cout &lt;&lt; "myOtherModel.Y[" &lt;&lt; i &lt;&lt; "]=" &lt;&lt; myOtherModel.Y[i] &lt;&lt; endl; return 0; } </code></pre> <p><strong>(2) defs.cpp:</strong></p> <pre><code>#include "defs.h" MyStruct ConstructModel() { MyStruct Model; double Y[2]={0.1,0.1}; Model.Y=Y; int n=2; Model.n=n; return Model; } </code></pre> <p><strong>(3) defs.h:</strong></p> <pre><code>#ifndef DEFS_H #define DEFS_H struct MyStruct { double *Y;//length (n+1) int n; }; MyStruct ConstructModel(); #endif </code></pre> <p><strong>Console output</strong></p> <p>On my machine (WinXP 32bit, MSVC2008), this gives:</p> <p>myModel goes first:</p> <p>myModel.Y[0]=1.12947e-307</p> <p>myModel.Y[1]=1.80243e-307</p> <p>myModel.n=2</p> <p>now myOtherModel:</p> <p>myOtherModel.Y[0]=0.1</p> <p>myOtherModel.Y[1]=0.1</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload