0
class Node {
public:
    float point[3];
};

int main(int argc, char** argv) {
    float p[3] = { 34, 90, 10 };
    Node *node = new Node();
    node->point = p;
    return 0;
}

This doesn't work as expected.

How should I initialize an array of a class object?

5
  • Use std::array<float, 3> instead Commented Aug 31, 2017 at 10:02
  • 1
    What happened to constructors? And using the right storage durations? Commented Aug 31, 2017 at 10:03
  • You have a memory leak. Commented Aug 31, 2017 at 10:05
  • @StoryTeller for 'float point[3]'? or for 'float p[3]'? Commented Aug 31, 2017 at 10:05
  • Both. Better yet, using point_t = std::array<float, 3>; Commented Aug 31, 2017 at 10:06

2 Answers 2

5

Array != pointer.

error: invalid array assignment
     node->point = p;

Here is the correct way to copy the array:

std::copy(std::begin(p),std::end(p), std::begin(node->point));

If you know the size of the array at compile time, you should use std::array:

class Node {
public:
    std::array<float,3> point;
};

std::array<float,3> p = {34.0f, 90.0f, 10.0f};
node->point = p;

Also, you may initialize the array via constructor and leave point as private data member:

// Ctor
Node(std::array<float,3> p) { point = p; }

// Calling
Node *node = new Node({34.0f, 90.0f, 10.0f});
// Or
std::array<float,3> p = {34.0f, 90.0f, 10.0f};
Node *node = new Node(p);

Otherwise, if you want to choose the size of the array at runtime, you should use std::vector.

Sign up to request clarification or add additional context in comments.

Comments

1

When using your design, you must copy the values as Node reserves memory.

Whether your approach is a good practise is an other question. Initializing from outside is somewhat strange

class Node {
  public:
    float point[3];
};

int main(int argc, char** argv) {
  float p[3] = { 34, 90, 10 };
  Node *node = new Node();
  memcpy (node->point, p, sizeof(p));
  return 0;
}

// alternative version

int main(int argc, char** argv) {
  Node *node = new Node();
  node->point[0] = 34.0f;
  node->point[1] = 90.0f;
  node->point[2] = 10.0f;

  return 0;
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.