You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言strtol函数运行后剩余内容疑问:为何ptr指向长度非0?

Understanding 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 ptr to 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:

  1. 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 with fgets(), it will include the newline character the user typed when pressing Enter. strtol() stops at that newline (since it's not a digit), so ptr points to it, and strlen(ptr) will be 1 (or 2 if it's \r\n on Windows).

  2. Typos in your string definition
    Double-check if you accidentally added extra characters when defining test, like " 4396 " (with a trailing space). In that case, strtol() stops at the trailing space, making ptr point to it, and strlen(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:30:03