Calculate Length of Array in C by Using Function

前端 未结 9 654
心在旅途
心在旅途 2020-12-04 18:20

I want to make a FUNCTION which calculates size of passed array.

I will pass an Array as input and it should return its length. I want a Function

int         


        
相关标签:
9条回答
  • 2020-12-04 19:19

    Is is very late. But I found a workaround for this problem. I know it is not the proper solution but can work if you don't want to traverse a whole array of integers.

    checking '\0' will not work here

    First, put any character in array at the time of initialization

    for(i=0;i<1000;i++)
    array[i]='x';
    

    then after passing values check for 'x'

    i=0;
    while(array[i]!='x')
    {
    i++;
    return i;
    }
    

    let me know if it is of any use.

    0 讨论(0)
  • 2020-12-04 19:21

    You can't do this once the array has decayed to a pointer - you'll always get the pointer size.

    What you need to do is either:

    • use a sentinel value if possible, like NULL for pointers or -1 for positive numbers.
    • calculate it when it's still an array, and pass that size to any functions.
    • same as above but using funky macro magic, something like:
      #define arrSz(a) (sizeof(a)/sizeof(*a)).
    • create your own abstract data type which maintains the length as an item in a structure, so that you have a way of getting your Array.length().
    0 讨论(0)
  • 2020-12-04 19:23

    Not possible. You need to pass the size of the array from the function, you're calling this function from. When you pass the array to the function, only the starting address is passed not the whole size and when you calculate the size of the array, Compiler doesn't know How much size/memory, this pointer has been allocated by the compiler. So, final call is, you need to pass the array size while you're calling that function.

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