Jonas
Jonas

Reputation: 1069

Error C2075: array initialization needs curly braces

I want to reverse a 2d array of type char using std::reverse() function in the STL algorithm.

#include <iostream>
#include <algorithm>

int main()
{
    char array[10][5];

    initiate_array(array);              // this takes care of initializing array

    std::reverse(array, array + 10);    // <- error C2075

    return 0;
}

But I keep getting this error: C2075: '_Tmp' : array initialization needs curly braces which I never encountered before!

I use MSVC++ 2008 to compile my code.

Upvotes: 0

Views: 5343

Answers (1)

David
David

Reputation: 28178

The root of the problem is that arrays cannot be assigned to one another. Let's consider how std::reverse might be implemented:

template<class BidirectionalIterator>
void reverse(BidirectionalIterator first, BidirectionalIterator last)
{
    while ((first != last) && (first != --last)) {
        std::swap(*first++, *last);
    }
}

and std::swap needs to be able to assign whatever arguments you give it, in order to swap them. In your case you have an array of arrays; So it's trying to swap the char[5] array at array[0] with the one at array[10], which is not valid C++.

However, in C++11 this does work as expected; not because you can now assign arrays, but because std::swap has gained an overload that makes it work for arrays, effectively mapping to std::swap_ranges. But you should realize that this is not just swapping pointers around, it's swapping the array type individually (chars in your case).

Upvotes: 3

Related Questions