Reputation: 3
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
Reputation: 726579
This function will not help you find the length of just any array - only some very specific ones:
char
,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