Reputation: 736
index = {27,27,27,27,27}; //as many as rootsize
Compiler gives me an error when I try this in a function. Index is globally initialized in the same file with:
int index[5];
error: expected expression index = {27,27,27,27,27}; //as many as rootsize
Is this not legal? How would I set an array to some values all at once? Would I need a loop?
Upvotes: 1
Views: 202
Reputation: 311078
In C++ you can use standard class std::array
declared in header <array>
.
For example
#include <array>
//...
std::array<int, 5> index;
//...
index = { 27, 27, 27, 27, 27 };
Otherwise you can use for example standard algorithms std::fill
or std::fill_n
declared in header <algorithm>
to fill the array with a value.
For example
#include <algorithm>
#include <iterator>
//...
int index[5];
//...
std::fill( std::begin( index ), std::end( index ), 27 );
// or
std::fill( index, index + 5, 27 );
Or
#include <algorithm>
//...
int index[5];
//...
std::fill_n( index, 5, 27 );
In C you can also enclose the array in a structure and use a compound literal. For example
struct array_t
{
int index[5];
} a;
//...
a = ( struct array_t ){ { 27, 27, 27, 27, 27 } };
for ( size_t i = 0; i < 5; i++ ) printf( "%i ", a.index[i] );
Of course you can initialize the array when it was declared
int index[5] = { 27, 27, 27, 27, 27 };
Upvotes: 2
Reputation: 239201
You cannot directly assign to an array. You can, however, memcpy()
to it from a compound literal:
#include <string.h>
memcpy(index, (int [5]){ 27, 27, 27, 27, 27 }, sizeof index);
Note that compound literals like this are a C feature, but not C++.
Upvotes: 5
Reputation: 167
Just write int index[5] = {27,27,27,27,27}
. and your problem resolved.
Upvotes: 2
Reputation: 19874
You can't initialize array as you are doing it because array name can't be a modifiable lvalue in C.
int index[5] = {27,27,27,27,27};
is a valid initialization
Upvotes: 2