Mario Tanev
Mario Tanev

Reputation: 3

Finding the length of an array using this function

Can anyone explain to me how to call the following function to find the length of an array? Thanks!

int len(char* s)
{
    int k = 0;
    while (*s)
    {
        k++;
        s++;
    }
    return k;
}

Upvotes: 0

Views: 55

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

This function will not help you find the length of just any array - only some very specific ones:

  • It needs to be an array of char,
  • It needs to have non-zero values in all its elements except the last one
  • The last element of the array must be zero.

In C arrays like that are created when you do this:

char array[] = "12345";

This is a six-element character array, with five initial elements occupied by non-zero character codes, and the sixth element occupied by zero.

Now the algorithm becomes clear: count elements until you hit zero, include zero in the count, and return the result:

char array[] = "12345";
int res = len(array);

Upvotes: 1

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

"can anyone explain me how to call this function to find the length of an array?"

You can call it like this

char* array = "Hello World!";
int length = len(array);

Upvotes: 1

Related Questions