C语言strtol函数运行后剩余内容疑问:为何ptr指向长度非0?
strtol() Behavior with Leading Whitespace Let's break down why you're seeing that unexpected strlen(ptr) result—this is a common gotcha with how strtol() processes input strings.
First, let's recap exactly what strtol() does step-by-step for your input " 4396":
- It skips all leading whitespace characters (in your case, the single space at the start of the string).
- Then it parses numeric characters until it hits a character that can't be part of a base-10 number.
- Finally, it sets
ptrto point to that first non-numeric character.
In an ideal scenario where your string is exactly " 4396" (space + "4396" + null terminator \0), strtol() would parse all the digits and set ptr to point directly at the \0. That would make strlen(ptr) return 0.
So why are you seeing a non-zero length? There are two likely culprits:
Your string has hidden trailing characters
Maybe the actual string you're testing isn't just" 4396"—it might have invisible characters at the end, like a newline (\n), carriage return (\r), or an extra space. For example, if you read the string from user input withfgets(), it will include the newline character the user typed when pressing Enter.strtol()stops at that newline (since it's not a digit), soptrpoints to it, andstrlen(ptr)will be 1 (or 2 if it's\r\non Windows).Typos in your string definition
Double-check if you accidentally added extra characters when definingtest, like" 4396 "(with a trailing space). In that case,strtol()stops at the trailing space, makingptrpoint to it, andstrlen(ptr)returns 1.
How to debug this
Add a line to print exactly what ptr is pointing to—this will reveal any hidden characters:
printf("ptr points to: '%s'\n", ptr);
If you see something like ' ' (a blank line), that's a newline. If you see ' ', that's a trailing space.
Quick fix example
If you want to ensure ptr ends up at the null terminator, make sure your input string has no extra characters after the digits:
char *test = " 4396"; // No trailing spaces or invisible characters char *ptr; long result = strtol(test, &ptr, 10); // Use long instead of int to match strtol's return type printf("%ld\n", result); printf("%zu\n", strlen(ptr)); // %zu is correct for size_t (strlen's return type)
This should output 4396 and 0 as expected.
Also, a quick note: strtol() returns a long value, so assigning it directly to an int can cause overflow if the parsed number is larger than INT_MAX. Using long for result is safer.
内容的提问来源于stack exchange,提问作者Ioce

