Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array not holding initialized values

Tags:

c++

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;
}
like image 936
MrMoe Avatar asked Aug 01 '17 17:08

MrMoe


2 Answers

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;
}
like image 174
ChrisB Avatar answered Sep 28 '22 02:09

ChrisB


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

  • float array1[]={0.2,1.3}; is unused
  • StructEx.array1[0] and StructEx.array1[0] are uninitialized

In the constructor put this

array1[0]=0.2;
array1[1]=1.3;
like image 40
Ely Avatar answered Sep 28 '22 03:09

Ely