0

I'm trying to make my Transpose function take pointers instead of std::arrays. And the reason I want to do this is because then I can pass it a pointer or std::array via the .data() function.

Currently I have the following and it works using both 2D and 1D arrays for transposing in place or to a new array.. However, converting the below code to take pointers instead gives a memory access violation error.

Can someone explain the difference and why the below is not equal to my pointer versions (below this):

#include <iostream>
#include <array>

template<typename T, std::size_t Size>
void Transpose(std::array<T, Size> &Data)
{
    int Width = sqrt(Size);
    for (int I = 1; I < Width; ++I)
    {
        for (int J = 0; J < I; ++J)
        {
            std::swap(Data[I * Width + J], Data[J * Width + I]);
        }
    }
}

template<typename T, std::size_t Size>
void Transpose(std::array<std::array<T, Size>, Size> &Data)
{
    for (int I = 0; I < Size; ++I)
    {
        for (int J = 0; J < I; ++J)
        {
            std::swap(Data[I][J], Data[J][I]);
        }
    }
}

However converting to the below does not work when I use a pointer :S

template<typename T>
void Transpose(T* Data, std::size_t Size)
{
    int Width = sqrt(Size);
    for (int I = 1; I < Width; ++I)
    {
        for (int J = 0; J < I; ++J)
        {
            std::swap(Data[I * Width + J], Data[J * Width + I]);
        }
    }
}

template<typename T>
void Transpose(T** Data, std::size_t Size)
{
    for (int I = 0; I < Size; ++I)
    {
        for (int J = 0; J < I; ++J)
        {
            std::swap(Data[I][J], Data[J][I]);
        }
    }
}

Can anyone please explain the difference and why the T** one does not work?

Brandon
  • 22,723
  • 11
  • 93
  • 186
  • In what way is it not equal (besides the double pointer)? Are you getting different outputs, errors? – David G Jun 09 '13 at 18:00

1 Answers1

3

A two-dimensional array doesn't decay into a double pointer. It decays into T*[]. For an explanation, see this thread.

You'll have to change the faulty line to:

void Transpose(T* Data[], std::size_t Size)

or (so the length can be deduced)

template <typename T, std::size_t Size1, std::size_t Size2>
void Transpose(T (&Data)[Size1][Size2])
Community
  • 1
  • 1
David G
  • 94,763
  • 41
  • 167
  • 253