Reputation: 49
I've got some very simple c++ code to show the problem. I initialize my array with values in the ctor. But when I try to access the array in main, those values are replaced with random numbers. Why?
//Example to figure out why initialization values are disappearing
#include <iostream>
struct Struct1
{
float array1[2];
//ctor
Struct1();
};
Struct1::Struct1()
{
float array1[] = {0.2,1.3};
}
int main()
{
Struct1 StructEx;
std::cout<<StructEx.array1[0]<<' ';
std::cout<<StructEx.array1[1]<<std::endl;
return 0;
}
Upvotes: 4
Views: 186
Reputation: 11174
Switch on the warnings (-Wall
) when compiling, and you will see
float array1[]={0.2,1.3};
is unusedStructEx.array1[0]
and StructEx.array1[0]
are uninitializedIn the constructor put this
array1[0]=0.2;
array1[1]=1.3;
Upvotes: 1
Reputation: 498
As @crashmstr mentioned, you do not initialise the member of the structure, but a local variable. The following code should work:
struct Struct1
{
float array1[2];
//ctor
Struct1();
};
Struct1::Struct1()
: array1 ({0.2,1.3})
{
}
int main()
{
Struct1 StructEx;
std::cout<<StructEx.array1[0]<<' ';
std::cout<<StructEx.array1[1]<<std::endl;
return 0;
}
Upvotes: 6