I want to parse an int from a string (char*) in C. I’m writing a linux kernel module for embedded linux. I’m trying to use simple_strtol found here.
My tokens I’m parsing in an ideal situation will be numbers. The problem I have is "0" is a valid input. strtol returns 0 if a value could not be parsed (error). So that means that the following code:
char* token = "should_fail";
char **endptr;
char value = simple_strtol(token, endptr, 10); // 10 is the base to convert to
if (!**endptr){
printf("failed!");
} else {
printf(value);
}
char* token = "0"; // should pass
char **endptr;
char value = simple_strtol(token, endptr, 10); // 10 is the base to convert to
if (!**endptr){
printf("failed!");
} else {
printf(value);
}
prints out 0 in both cases, when it should fail in the first case. I am trying to use that *endptr argument to check to see if the conversion is successful, but its not working. According to what I’ve researched, *endptr is “A pointer to the end of the parsed string will be placed here”. And I believe if a conversion failed the pointer will point to nothing so I can identify that failure.
Does anybody know how I can parse "0" properly and get a return value of 0 while still identifying a failed parse, and not having it return 0?
You should not create a pointer-to-pointer variable for
endptr. Instead declare a single pointer, and pass the address of that with the unary&operator:I didn’t read the manual page but basically copied what the OP had used. Froom the manual page:
This means that if
strtol(or your alternative if it’s working as specified) returns0andendptr == tokenthen the string was invalid.So the check should be