Suppose i have array of characters. say char x[100]
Now, i take input from the user and store it in the char array. The user input is less than 100 characters. Now, if i want to do some operation on the valid values, how do i find how many valid values are there in the char array. Is there a C function or some way to find the actual length of valid values which will be less than 100 in this case.
Yes, C has function
strlen()(from string.h), which gives you number of characters in char array. How does it know this? By definition, every C “string” must end with the null character. If it does not, you have no way of knowing how long the string is or with other words, values of which memory locations of the array are actually “useful” and which are just some dump. Knowing this,sizeof(your_string)returns the size of the array (in bytes) and NOT length of the string.Luckily, most C library string functions that create “strings” or read input and store it into a char array will automatically attach null character at the end to terminate the “string”. Some do not (for example
strncpy()). Be sure to read their descriptions carefully.Also, take notice that this means that the buffer supplied must be at least one character longer than the specified input length. So, in your case, you must actually supply char array of length 101 to read in 100 characters (the difference of one byte is for the null character).
Example usage:
strlen() is defined as:
As you see, the end of a string is found by searching for the first null character in the array.