+ 1

Why strchr shows error if character not found in c?

is there another way to achieve what i am trying to( see code)? https://code.sololearn.com/cKB5HoI3DE0r/?ref=app https://code.sololearn.com/cKB5HoI3DE0r/?ref=app

1st Dec 2021, 2:24 AM
gaurav kumar
gaurav kumar - avatar
1 Resposta
+ 4
strchr() returns a null pointer if the character is not found in the string. Since 'p' is not present in `str`, strchr(str, 'p') returns a null pointer, which you are then dereferencing. Dereferencing a null pointer results in a segmentation fault. You need to check if the pointer returned by strchr() is not a null pointer. You don't need to compare the character at the returned pointer with 'p' as it is guaranteed that it will be 'p' or a null pointer. Fixed code: https://code.sololearn.com/cA8oVgynbiPX/?ref=app Another example of using strchr() is here: https://www.cplusplus.com/reference/cstring/strchr/
1st Dec 2021, 3:37 AM
XXX
XXX - avatar