ScottishTapWater
ScottishTapWater

Reputation: 4846

Can't initialise an array

Okay, I'm pretty new when it comes to C++ (having moved over from VB) and I can't seem to work out how to populate an array without doing:

array[0] = 1
array[1] = 2 

etc etc

So as could be expected, I have tried this:

float posVector[3]; //Declared outside of int main() as needs to be global
posVector = {0.0f,0.0f,0.0f}; //Inside int main()

Which is causing this error to be displayed:

extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default]

Nothing I have been able to locate online so far has been of any help. So any advice you can give me on fixing this will be appreciated!

Upvotes: 2

Views: 103

Answers (4)

HelloWorld
HelloWorld

Reputation: 1863

Once the array is declared it cannot be initialized using the initializer list. You can go with

float posVector[] = {0.0f,0.0f,0.0f};

or even better go with std::vector:

#include <vector>

std::vector<float> posVector = {0.0f,0.0f,0.0f};

Upvotes: 5

SergeyA
SergeyA

Reputation: 62613

As far as I understand, the question is not about INITIALIZING the array, but about assigning the array after it was already created. The answer is 'no way'. Arrays can not be assigned after they are initialized. However, arrays of fixed sizes some time might be more adequately presented as structs, and this is exactly the case! Coordinates are much better presented as structs!

Not commenting on the neccessity of global variable (most likely, not needed) here is the way to make it work:

struct Coordinate {
    float x;
    float y;
    float z;
};

Coordinate coord;

void foo() {
    coord = {1, 2, 3};
}

Upvotes: 0

user5378236
user5378236

Reputation:

Shortest way i think: float posVector[] { 0.0f,0.0f,0.0f };

Upvotes: 0

Aram Antonyan
Aram Antonyan

Reputation: 159

It can be done like this:

float f[] = {1.0, 2.0, 3.0, 4.0, 5.0};

Upvotes: 1

Related Questions