+ 2

What is the real use of strnlen() ??

27th Dec 2018, 12:59 PM
CHANDAN MEHER
CHANDAN MEHER - avatar
4 Réponses
+ 2
strnlen (s,n) limits scanning the end of string to n characters. It is useful for finding strings shorter than n. Also it is a memory safe implemetation of strlen, which can prevent looking for the trailing zero outside of allocated memory, so prevents possible application crash.
27th Dec 2018, 2:36 PM
Микола Федосєєв
Микола Федосєєв - avatar
+ 4
Rewa Mathur Actually I missed the 'n' in strnlen! Lol
27th Dec 2018, 3:06 PM
Babak
Babak - avatar
+ 3
A useful example would be looking through a buffer from beginning till the last non-null character ¹ for some particular characters. Extending/modifying the Rewa's example: #include <stdio.h> #include <ctype.h> #define MAX 1000 int main() { char s[MAX]; size_t i, digit = 0; printf("Enter a string: "); fgets(s, MAX, stdin); size_t length = strlen(s); for (i = 0; i < length; ++i) { if (isdigit(s[i])) ++digit; } printf("Number of digit(s) in s is: %zu", digit); } ______ ¹ `strlen` searches for the first '\0' character
27th Dec 2018, 2:16 PM
Babak
Babak - avatar
+ 2
Oh yeah?! -1 for not giving credit. So, you know how to Google and find your answer on Stackoverflow, but you don't know how to copy/paste the link for credit? https://stackoverflow.com/questions/26349367/what-is-the-real-use-of-strnlen
28th Dec 2018, 5:40 AM
Babak
Babak - avatar