0

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;
}
2
  • How to call that function? Write len(s) where s is a pointer to a char array. Commented Feb 7, 2015 at 13:05
  • 1
    This function can't tell you the length of an array. It looks like a (bad) substitute for strlen() though, which gives you the length of a C-style string. Using C-style strings is the first thing to get rid of when learning C++ though... Commented Feb 7, 2015 at 13:19

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.