0

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.

Jonas
  • 1,019
  • 4
  • 20
  • 33
  • You probably want a vector of strings. The problem is that the type the array is holding is another array. – chris Jun 15 '12 at 22:53
  • @chris yeah, `array` is a pointer to an array of pointers. I want to reverse the content of this array. can't I do that? – Jonas Jun 15 '12 at 22:57
  • 2
    @Jonas no it's not. `array` is an array of arrays. An array is not the same as a pointer. – Luchian Grigore Jun 15 '12 at 22:57
  • 1
    @Jonas, You're in desperate need of this: http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c. It goes into the intricacies, not just basic use. – chris Jun 15 '12 at 23:02
  • can we see the initiate function? – EvilTeach Jun 15 '12 at 23:24
  • @EvilTeach just a `for` loop with `strcpy(array[i], "...");` inside of it. argument of the function is `char array[][5]` – Jonas Jun 16 '12 at 00:15

1 Answers1

3

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).

David
  • 27,652
  • 18
  • 89
  • 138