Length of array in function argument

前端 未结 8 1912
终归单人心
终归单人心 2020-11-21 23:05

This is well known code to compute array length in C:

sizeof(array)/sizeof(type)

But I can\'t seem to find out the length of the array pass

8条回答
  •  误落风尘
    2020-11-21 23:37

    This is a old question, and the OP seems to mix C++ and C in his intends/examples. In C, when you pass a array to a function, it's decayed to pointer. So, there is no way to pass the array size except by using a second argument in your function that stores the array size:

    void func(int A[]) 
    // should be instead: void func(int * A, const size_t elemCountInA)
    

    They are very few cases, where you don't need this, like when you're using multidimensional arrays:

    void func(int A[3][whatever here]) // That's almost as if read "int* A[3]"
    

    Using the array notation in a function signature is still useful, for the developer, as it might be an help to tell how many elements your functions expects. For example:

    void vec_add(float out[3], float in0[3], float in1[3])
    

    is easier to understand than this one (although, nothing prevent accessing the 4th element in the function in both functions):

    void vec_add(float * out, float * in0, float * in1)
    

    If you were to use C++, then you can actually capture the array size and get what you expect:

    template 
    void vec_add(float (&out)[N], float (&in0)[N], float (&in1)[N])
    {
        for (size_t i = 0; i < N; i++) 
            out[i] = in0[i] + in1[i];
    }
    

    In that case, the compiler will ensure that you're not adding a 4D vector with a 2D vector (which is not possible in C without passing the dimension of each dimension as arguments of the function). There will be as many instance of the vec_add function as the number of dimensions used for your vectors.

提交回复
热议问题