2

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’?

1
  • I believe double[] wDist = new double[8]; is a syntax error. Are you sure that's exactly what's in your code? Could it be double* wDist = ...? Aug 23, 2012 at 3:38

3 Answers 3

4

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;
}
1

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]) {}
};
2
  • Better than this would be to make wDist be a std::vector<double>.
    – Mankarse
    Aug 23, 2012 at 4:02
  • @Man only if you want to hold a variable number of elements. I think std::array would be best in this case.
    – Antimony
    Aug 23, 2012 at 14:13
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.