Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does strlen() apply on character arrays also?

strlen() is a function argument should be a string but why is it also applicable to character arays ?
For eg

char abc[100];   
cin.getline(abc,100);  
len=strlen(abc);  

If it works for character array and tells the number of elements , can it be used for int array also?

Note : I am using TurboC++

like image 922
eatq Avatar asked Jan 28 '26 03:01

eatq


1 Answers

It's important to understand what a string is. The C standard defines a string as "a contiguous sequence of characters terminated by and including the first null character". It's a data format, not a data type; a C-style string may be contained in an array of char. This is not to be confused with the C++-specific type std::string, defined in the <string> (note: no .h suffix) header.

The <string.h> header, or preferably the <cstring> header, is incorporated into C++ from the C standard library. The functions declared in that header operate on C-style strings, or on pointers to them.

The argument to strlen is of type char*, a pointer to a character. (It's actually const char*, meaning that strlen promises not to modify whatever it points to.)

An array expression is, in most contexts, implicitly converted to a pointer to the initial element of the array. (See section 6 of the comp.lang.c FAQ for the details.)

The char* argument that you pass to strlen must point to the initial element of an array of characters, and there must be a null character ('\0') somewhere in the array to mark the end of the string. It computes the number of characters up to, but not including, the null terminator.

It does not (and cannot) compute the number of elements in an array, only the number of characters in a string -- which it can do only if the array actually contains a valid string. If there is no null character anywhere in the array, or if the pointer is null or otherwise invalid, the behavior is undefined.

So when you write:

char abc[100];
cin.getline(abc,100);
len=strlen(abc);

the call to cin.getline ensures that the array abc contains a properly null-terminated string. strlen(abc) calls strlen, passing it the address of the initial character; it's equivalent to strlen(&abc[0]).

No, strlen will not work on an array of int. For one thing, that would pass an int* value, which doesn't match the char* that strlen requires, so it probably wouldn't compile. Even ignoring that, strlen counts characters, not ints. (You can write your own similar function that counts ints if you like, but it still has to have some way to find the end of the elements that you're interested in counting. It doesn't have access to the actual length of the array unless you pass it explicitly.)

like image 103
Keith Thompson Avatar answered Jan 30 '26 19:01

Keith Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!