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?

1
  • In what way is it not equal (besides the double pointer)? Are you getting different outputs, errors? Commented Jun 9, 2013 at 18:00

1 Answer 1

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])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.