Hi everyone,
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.
My apologies should my code be scrambled -- I have been struggling a bit with formatting it properly.
I'd be grateful if someone could help me understand and rectify this.
Best, Jo
(1) main.cpp:
#include "iostream"
#include "defs.h"
using namespace std;
int main()
{
MyStruct myModel=ConstructModel();
cout << endl << "myModel goes first:" << endl;
for(int i=0; i<myModel.n; i++)
cout << "myModel.Y[" << i << "]=" << myModel.Y[i] << endl;
cout << "myModel.n=" << myModel.n << endl;
MyStruct myOtherModel;
myOtherModel.n=2; double Y[2]={0.1,0.1};
myOtherModel.Y=Y;
cout << endl << "now myOtherModel:" << endl;
for(int i=0; i<myModel.n; i++)
cout << "myOtherModel.Y[" << i << "]=" << myOtherModel.Y[i] << endl;
return 0;
}
(2) defs.cpp:
#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;
}
(3) defs.h:
#ifndef DEFS_H
#define DEFS_H
struct MyStruct
{
double *Y;//length (n+1)
int n;
};
MyStruct ConstructModel();
#endif
Console output
On my machine (WinXP 32bit, MSVC2008), this gives:
myModel goes first:
myModel.Y[0]=1.12947e-307
myModel.Y[1]=1.80243e-307
myModel.n=2
now myOtherModel:
myOtherModel.Y[0]=0.1
myOtherModel.Y[1]=0.1