Get the length of the array that contains element 0 when going to the function

Is there a way to print the length of an array that contains element 0, and this array was passed to a function that can only have one argument as an array?

Example:

int arrLen(int arr[])
{
    //get size here;
}

int main()
{
    int arr[]={0,1,2,3,4,5};
    arrLen(arr);
}

In C ++, there is a restriction that we cannot compare array elements with NULL if it has zero, but still asks if there is a way to do this. I can only pass an array of functions - this is my limitation.

+4
source share
6 answers

In your example, you can use a function template to get what you want:

template <size_t N>
int arrLen(int (&arr)[N])
{
    return N;
}
+5
source

, . , , , . , sizeof - , sizeof , .

, , '\0', , ( , , , , -1 - ). .

+3

C, , . , .

:

int arr[] = {-1,0,1,2,3,4,5};
arr[0] = sizeof(arr) / sizeof(arr[0]) - 1; 

arr[0].

+2

, :

  • - , .
  • . , , . , C \0 .

, , (, INT_MIN ), , . .

+2

, , , int ( ), -1, . arrLen, ( , , int):

int arrLen(int arr[])
{
    int size = 0;
    int* p = arr;
    while (*p != -1) {
        ++size;
        ++p;
    }
    return size;
}

, , "" , :

int arr[]={0,1,2,3,4,5, -1 };
+2

, 1 , . , , . , , , , int .

- int ascii int, NULL '\ 0' '0', NULL .

, , .

0

Source: https://habr.com/ru/post/1526734/


All Articles