Passing a pointer representing a 2D array to a function in C++

后端 未结 5 817
别那么骄傲
别那么骄傲 2020-11-30 06:01

http://www.neilstuff.com/guide_to_cpp/notes/Multi%20Dimension%20Arrays%20and%20Pointer%20Pointers.htm

According to this site, I should be able to use the following c

5条回答
  •  青春惊慌失措
    2020-11-30 07:04

    In addition to Cubbi's detailed answer, the following way is just natural to pass a 2-dim array to a function:

    void dostuff(void *a1, int rows, int cols)
    {
        double (*a)[cols] = (double (*)[cols]) a1;
        // access them as a[0][0] .. a[rows-1][cols-1];
    }
    int main()
    {
        double stuff[3][3];
        dostuff(stuff, 3, 3);
    }
    

    You don't have to cast them in advance since the newest C++ (C++14) supports run-time sized arrays.

提交回复
热议问题