Reputation: 527
I define the following struct
struct CCPtDist
{
double[] wDist = new double[8];
};
And I want to build a "CCPtDist" variable called tmpPtDist and want to assign a double number to wDist:
CCPtDist tmpPtDist;
tmpPtDist.wDist[0] = 233.7;
But the g++ compiler returns an error: ‘struct CCPtDist’ has no member named ‘wDist’?
Upvotes: 2
Views: 182
Reputation: 69977
If you want a fixed-size (!) array as part of your struct, there is no need for dynamic allocation (i.e. new
):
struct CCPtDist
{
double wDist[8];
};
will suffice. However, note that the 8 values of this array are not initialized this way. They will contain random garbage. So better add a constructor that initializes the array:
struct CCPtDist
{
double wDist[8];
CCPtDist():wDist() {}
};
If your compiler supports it, using std::array
, which was introduced in C++11, might be a better approach, as described in SRN's answer.
Upvotes: 0
Reputation: 2455
As an alternative to a C-style array, you can use std::array
:
#include <array>
struct CCPtDist
{
std::array<double,8> wDist;
};
int main()
{
CCPtDist tmpdist;
tmpdist.wDist[0]=233.7;
}
Upvotes: 4
Reputation: 39451
There are a number of things wrong in the code. First off, if you declare an array as a member, the memory is allocated inline as part of the struct. You can't just assign an arbitrary pointer to it. Second off, I don't think you declared the array correctly anyway. Third, you need to put complex initialization like that in a constructor.
I'm surprised it doesn't give you a compile error on the double[] wDist = new double[8];
line.
Try changing it to something like this
struct CCPtDist
{
double* wDist;
CCPtDist(): wDist(new double[8]) {}
};
Upvotes: 1