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

后端 未结 5 820
别那么骄傲
别那么骄傲 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 06:58

    Regarding the edit: to pass this double stuff[3][3] to a C function, you could

    1) pass a pointer to the whole 2D array:

    void dostuff(double (*a)[3][3])
    {
    // access them as (*a)[0][0] .. (*a)[2][2]
    }
    int main()
    {
        double stuff[3][3];
        double (*p_stuff)[3][3] = &stuff;
        dostuff(p_stuff);
    }
    

    2) pass a pointer to the first 1D array (first row) and the number of rows

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

    3) pass a pointer to the first value in the first row and the number of both columns and rows

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

    (that this last option is not strictly standards-compliant since it advances a pointer to an element of a 1D array (the first row) past the end of that array)

    If that wasn't a C function, there'd be a few more options!

提交回复
热议问题