Length of array in function argument

前端 未结 8 1900
终归单人心
终归单人心 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:28

    First, a better usage to compute number of elements when the actual array declaration is in scope is:

    sizeof array / sizeof array[0]
    

    This way you don't repeat the type name, which of course could change in the declaration and make you end up with an incorrect length computation. This is a typical case of don't repeat yourself.

    Second, as a minor point, please note that sizeof is not a function, so the expression above doesn't need any parenthesis around the argument to sizeof.

    Third, C doesn't have references so your usage of & in a declaration won't work.

    I agree that the proper C solution is to pass the length (using the size_t type) as a separate argument, and use sizeof at the place the call is being made if the argument is a "real" array.

    Note that often you work with memory returned by e.g. malloc(), and in those cases you never have a "true" array to compute the size off of, so designing the function to use an element count is more flexible.

    0 讨论(0)
  • 2020-11-21 23:29
    int arsize(int st1[]) {
        int i = 0;
        for (i; !(st1[i] & (1 << 30)); i++);
        return i;
    }
    

    This works for me :)

    0 讨论(0)
  • 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 <size_t N>
    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.

    0 讨论(0)
  • 2020-11-21 23:42

    sizeof only works to find the length of the array if you apply it to the original array.

    int a[5]; //real array. NOT a pointer
    sizeof(a); // :)
    

    However, by the time the array decays into a pointer, sizeof will give the size of the pointer and not of the array.

    int a[5];
    int * p = a;
    sizeof(p); // :(
    

    As you have already smartly pointed out main receives the length of the array as an argument (argc). Yes, this is out of necessity and is not redundant. (Well, it is kind of reduntant since argv is conveniently terminated by a null pointer but I digress)

    There is some reasoning as to why this would take place. How could we make things so that a C array also knows its length?

    A first idea would be not having arrays decaying into pointers when they are passed to a function and continuing to keep the array length in the type system. The bad thing about this is that you would need to have a separate function for every possible array length and doing so is not a good idea. (Pascal did this and some people think this is one of the reasons it "lost" to C)

    A second idea is storing the array length next to the array, just like any modern programming language does:

    a -> [5];[0,0,0,0,0]
    

    But then you are just creating an invisible struct behind the scenes and the C philosophy does not approve of this kind of overhead. That said, creating such a struct yourself is often a good idea for some sorts of problems:

    struct {
        size_t length;
        int * elements;
    }
    

    Another thing you can think about is how strings in C are null terminated instead of storing a length (as in Pascal). To store a length without worrying about limits need a whopping four bytes, an unimaginably expensive amount (at least back then). One could wonder if arrays could be also null terminated like that but then how would you allow the array to store a null?

    0 讨论(0)
  • 2020-11-21 23:46

    Best example is here

    thanks #define SIZE 10

    void size(int arr[SIZE])
    {
        printf("size of array is:%d\n",sizeof(arr));
    }
    
    int main()
    {
        int arr[SIZE];
        size(arr);
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-21 23:49

    The array decays to a pointer when passed.

    Section 6.4 of the C FAQ covers this very well and provides the K&R references etc.


    That aside, imagine it were possible for the function to know the size of the memory allocated in a pointer. You could call the function two or more times, each time with different input arrays that were potentially different lengths; the length would therefore have to be passed in as a secret hidden variable somehow. And then consider if you passed in an offset into another array, or an array allocated on the heap (malloc and all being library functions - something the compiler links to, rather than sees and reasons about the body of).

    Its getting difficult to imagine how this might work without some behind-the-scenes slice objects and such right?


    Symbian did have a AllocSize() function that returned the size of an allocation with malloc(); this only worked for the literal pointer returned by the malloc, and you'd get gobbledygook or a crash if you asked it to know the size of an invalid pointer or a pointer offset from one.

    You don't want to believe its not possible, but it genuinely isn't. The only way to know the length of something passed into a function is to track the length yourself and pass it in yourself as a separate explicit parameter.

    0 讨论(0)
提交回复
热议问题