tags:

views:

528

answers:

8

I'm trying to initialize an int array with everything set at -1.

I tried the following, but it doesn't work. It only sets the first value at -1.

int directory[100] = {-1};

Why doesn't it work right?

+2  A: 

If you had a smaller number of elements you could specify them one after the other. Array initialization works by specifying each element, not by specifying a single value that applies for each element.

int x[3] = {-1, -1, -1 };

You could also use a vector and use the constructor to initialize all of the values. You can later access the raw array buffer by specifying &v.front()

std::vector directory(100, -1);

There is a C way to do it also using memset or various other similar functions. memset works for each char in your specified buffer though so it will work fine for values like 0 but may not work depending on how negative numbers are stored for -1.


You can also use STL to initialize your array by using fill_n. For a general purpose action to each element you could use for_each.

fill_n(directory, 100, -1);

Or if you really want you can go the lame way, you can do a for loop with 100 iterations and doing directory[i] = -1;

Brian R. Bondy
+1  A: 

It is working right. That's how list initializers work.

I believe 6.7.8.10 of the C99 standard covers this:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules;
  • if it is a union, the first named member is initialized (recursively) according to these rules.

If you need to make all the elements in an array the same non-zero value, you'll have to use a loop or memset.

Also note that, unless you really know what you're doing, vectors are preferred over arrays in C++:

Here's what you need to realize about containers vs. arrays:

  1. Container classes make programmers more productive. So if you insist on using arrays while those around are willing to use container classes, you'll probably be less productive than they are (even if you're smarter and more experienced than they are!).
  2. Container classes let programmers write more robust code. So if you insist on using arrays while those around are willing to use container classes, your code will probably have more bugs than their code (even if you're smarter and more experienced).
  3. And if you're so smart and so experienced that you can use arrays as fast and as safe as they can use container classes, someone else will probably end up maintaining your code and they'll probably introduce bugs. Or worse, you'll be the only one who can maintain your code so management will yank you from development and move you into a full-time maintenance role — just what you always wanted!

There's a lot more to the linked question; give it a read.

Mark Rushakoff
`vector`'s are not preferred over arrays. They are two different things. Whichever is best in my current situation is the preferred one.
GMan
+1  A: 

Can't do what you're trying to do with a raw array (unless you explicitly list out all 100 -1s in the initializer list), you can do it with a vector:

vector<int> directory(100, -1);

Additionally, you can create the array and set the values to -1 using one of the other methods mentioned.

Stephen
Yes you can, many different ways.
Brian R. Bondy
@Brian R. Bondy: Yes, of course, but that's just pedantry. memset,fill,for-loop are fine solutions, but they're not set at initialization. For a raw-array it's {-1,-1,...x100} or set them afterwards.
Stephen
ya, I guess at declaration time you have one.
Brian R. Bondy
+3  A: 

use vector of int instead a array.

vector<int> directory(100,-1);                       // 100 ints with value 1
sat
+11  A: 

I'm surprised at all the answers suggesting vector. They aren't even the same thing!

Use std::fill, from <algorithm>:

int directory[100];
std::fill(directory, directory + 100, -1);

Not concerned with the question directly, but you might want a nice helper function when it comes to arrays:

template <typename T, size_t N>
T* end(T (&pX)[N])
{
    return pX + N;
}

Giving:

int directory[100];
std::fill(directory, end(directory), -1);

So you don't need to list the size twice.

GMan
I'm surprised no one has suggested writing out -1 in the initializer list 100 times.
Brian R. Bondy
By the way check here: http://stackoverflow.com/questions/2489970/dyanamic-allocation-on-stack-on-run-time/2489989#2489989 where you say that you can't think of any case that a vector shouldn't be used. On that question the OP was asking about arrays too :)
Brian R. Bondy
Just a minor note that for this, `std::fill_n` is a little simpler: `std::fill_n(directory, 100, -1);`
Jerry Coffin
@Brian R. Bondy: I'm surprised nobody suggested doing `memset(directory, -1, ...)`. On 2's complement architecture this will actually set `int` values to `-1` :)
AndreyT
The difference between this question and the other one is that this question deals with a statically sized array.
Dennis Zickefoose
@Dennis: I understand the difference, it was just posted for humor given the strong stance about array vs vector difference.
Brian R. Bondy
One could also manually initialize an array of 5 integers, and then copy it 20 times to the 100'er one. Though that would probably be disgusting :)
Johannes Schaub - litb
A: 

I would suggest using array. For three reasons:
1. array provides runtime safety against index-out-of-bound in subscripting (i.e. operator[]) operations,
2. array automatically carries the size without requiring to pass it separately
3. And most importantly, array provides the fill() method that is required for this problem

#include <array>
#include <assert.h>

typedef std::array< int, 100 > DirectoryArray;

void test_fill( DirectoryArray const & x, int expected_value ) {
    for( size_t i = 0; i < x.size(); ++i ) {
        assert( x[ i ] == expected_value );
    }
}

int main() {
    DirectoryArray directory;
    directory.fill( -1 );
    test_fill( directory, -1 );
    return 0;
}

Using array requires use of "-std=c++0x" for compiling (applies to the above code).

If that is not available or if that is not an option, then the other options like std::fill() (as suggested by GMan) or hand coding the a fill() method may be opted.

ArunSaha
And most important for me is that it *is* a native array inside. Allocated all on stack and such, if the array instance is on stack. Of course, if there is no C++0x support, `boost::array` or an own wrapped C array will do it too.
Johannes Schaub - litb
@Johannes: Yes, that <array> contains a native array inside, is an important point. I missed to mention that. Thanks!
ArunSaha
+1  A: 

If you really need arrays, you can use boosts array class. It's assign member does the job:

boost::array<int,N> array; // boost arrays are of fixed size!
array.assign(-1);
jopa
+2  A: 

It does work right. Your expectation of the initialiser is incorrect. If you really wish to take this approach, you'll need 100 comma-separated -1s in the initialiser. But then what happens when you increase the size of the array?

Johnsyweb
add more -1s :)
Brian R. Bondy
<tongue position="cheek">We took all of those developers around the back and shot them some time ago! </tongue>
Johnsyweb