when do we need to pass the size of array as a parameter

后端 未结 8 2117
青春惊慌失措
青春惊慌失措 2020-12-01 19:00

I am a little bit confused about pass an array in C/C++. I saw some cases in which the signature is like this

void f(int arr[])

some is lik

8条回答
  •  广开言路
    2020-12-01 20:00

    C and C++ are not the same thing. They have some common subset, though. What you observed here is that the "first" array dimension when passed to a function always results just in a pointer being passed. The "signature" (C doesn't use this term) of a function declared as

    void toto(double A[23]);
    

    is always just

    void toto(double *A);
    

    That is that the 23 above is somewhat redundant and not used by the compiler. Modern C (aka C99) has an extension here that lets you declare that A always has 23 elements:

    void toto(double A[static 23]);
    

    or that the pointer is const qualified

     void toto(double A[const 23]);
    

    If you add other dimension the picture changes, then the array size is used:

    void toto(double A[23][7]);
    

    in both C and C++ is

    void toto(double (*A)[7]);
    

    that is a pointer to an array of 7 elements. In C++ these array bounds must be an integer constant. In C it can be dynamic.

    void toto(size_t n, size_t m, double A[n][m]);
    

    They only thing that you have to watch here is that here n and m come before A in the parameter list. So better you always declare functions with the parameters in that order.

提交回复
热议问题