An array containing no initialized values

I have very simple C ++ code to show the problem. I initialize my array with values ​​in ctor. But when I try to access the array basically, these 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; } 
+5
source share
2 answers

As @crashmstr mentioned, you are not initializing a 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; } 
+6
source

Turn on warnings ( -Wall ) when compiling, and you will see

  • float array1[]={0.2,1.3}; not used
  • StructEx.array1[0] and StructEx.array1[0] initialized

In the constructor, put this

 array1[0]=0.2; array1[1]=1.3; 
+1
source

Source: https://habr.com/ru/post/1270445/


All Articles