DzikiChrzan
DzikiChrzan

Reputation: 3107

Writing new values into array

This is a fragment of my code:

typedef float point2[2];

point2 a = {-90, -90};
point2 b = {-90, 90};
point2 c = {90, 90};
point2 d = {90, -90};

glBegin(GL_POLYGON);
    glVertex2fv(a);
    glVertex2fv(b);
    glVertex2fv(c);
    glVertex2fv(d);
glEnd();

And this goes really well. But later when I try to write new values into these arrays, like:

a = {-66, -66};
b = {-66, 66};

And here I get an error:

error: assigning to an array from an initializer list

And I understand, that I can't assign values directly to an array after its declaration. But how this should looks like?

Upvotes: 1

Views: 1174

Answers (6)

cdonat
cdonat

Reputation: 2822

When your case is really about points in a plain, you schould prefer to use a class instead of an array.

class point2 {
    private:
        float x_;
        float y_;
    public:
        point2(const float x, const float y): 
            x_{x}, y_{y} {};
        point2(const point2& o): 
            x_{o.x_}, y_{o.y_} {};

        operator = (const point2& o) {
            x_ = o.x_;
            y_ = o.y_;
        }
        // ...
};


point2 a = {90.0, 90.0}; // initialize a

a = {45.0, 45.0}; // untested, should work
a = point2{45.0, 45.0} // will work.

As you see, this will give you a more natural and expressive interface. Such interfaces always improve readability and maintaiability.

Upvotes: 2

Chris Drew
Chris Drew

Reputation: 15334

You can't assign to an array using an initializer list. But if you use std::array instead of a C array then this is possible:

#include <array>
typedef std::array<float, 2> point2;

point2 a = {-90.0, -90.0};
a = {-66, -66};

And you can still pass it to a function like glVertex2fv that takes a pointer to an array by using std::array::data:

glVertex2fv(a.data());

Live demo.

Upvotes: 3

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122178

You cant use initializer list once the array is initialized, just do:

a[0] = -66;
a[1] = -66;

Upvotes: 2

Roman Pustylnikov
Roman Pustylnikov

Reputation: 1932

This is possible during initialization only. Use:

a[0]= - 66;
a[1] = -66;

However you can create temporary array and then copy it.

point2 tmp = {-66, -66 }
System.arraycopy( tmp, 0, a, 0, src.length );

But it looks like an overkill for such a task.

Upvotes: 1

Humam Helfawi
Humam Helfawi

Reputation: 20264

you should do something like:

a[0] =-66;
a[1]=-66;

Upvotes: 1

Algirdas Preidžius
Algirdas Preidžius

Reputation: 1767

In those statements, you are not assigning values to an array, you are initializing that array. Changing values in an array can be done like this:

a[0] = -66;
a[1] = -66;

Upvotes: 2

Related Questions