Search code examples
c++gnuplot

How does gnuplot C++ api know where a pointer ends?


I want to draw a heatmap in C++ and I came across this code : Plotting heatmap with Gnuplot in C++

In gp.send2d(frame); all what the function send2d is seeing is a float*, so how does it know the dimensions (4x4) ? Or even that it can access safely 16 elements ?


Solution

  • The size of the array is part of its type. In the example you link to frame is a float[4][4]. Since send2d() is declared as

    template <typename T> Gnuplot &send2d(const T &arg)
    

    It will deduce the type of T to be float[4][4] and make arg a reference to that. Expanded out that would look like

    Gnuplot &send2d(const float (&arg)[4][4])
    

    Which shows that arg is a reference 2d array. There is no decay to a pointer here since we have a reference.

    Here is an example that shows that using references maintains the array trype instead of decaying to a pointer

    template<typename T>
    void foo(T & arr_2d)
    {
        for (auto& row : arr_2d)
        {
            for (auto& col : row)
                std::cout << col << " ";
            std::cout << "\n";
        }
    }
    
    
    int main() 
    {
        int bar[2][2] = {1,2,3,4};
        foo(bar);
    }
    

    Output:

    1 2 
    3 4 
    

    Live Example