c - strtoul() 函数中的第二个参数有什么作用?

标签 c hex strtoul

根据this document ,

The second argument (char **endptr) seems to be a waste of space! If it is set to NULL, STRTOL seems to work its way down the string until it finds an invalid character and then stops. All valid chars read are then converted if the string starts with an invalid character the function returns ZERO (0).

这意味着以下代码应将 2 检测为十六进制数:

int main()
{
    char * string = "p1pp2ppp";

    unsigned integer = strtoul(string, NULL, 16);

    printf("%u", integer);

    return 0;
}

但是,它返回零。

为什么?

最佳答案

手册页对第二个参数进行了以下说明:

If endptr is not NULL, strtol() stores the address of the first invalid character in *endptr. If there were no digits at all, strtol() stores the original value of nptr in *endptr (and returns 0). In particular, if *nptr is not '\0' but **endptr is '\0' on return, the entire string is valid.

例如:

char str[] = "123xyz45";
char *p;
long x = strtol(str, &p, 10);
printf("x=%ld\n", x);
printf("p - str = %d\n", p - str);
printf("*p = %c\n", *p);
printf("p (as string) = %s\n", p);

输出:

x=123
p - str = 3
*p = x
p (as string) = xyz45

我们可以看到,当strtol返回时,p指向str中第一个无法转换的字符。这可用于一次解析字符串,或者查看是否可以转换整个字符串或是否有一些额外的字符。

在您的示例中,string 中的第一个字符(即“p”)不是基于 10 的数字,因此不会转换任何内容,并且函数返回 0。

关于c - strtoul() 函数中的第二个参数有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55573174/

相关文章:

c - sscanf 和尾随字符

python - 十六进制数的按位异或

c++ - 使用 sprintf 打印十六进制值的便携方式

Python 将十六进制字符串转换为十六进制小端字节码

c - 如何有效地将十六进制编码的字符串转换为 C 中的字符串

c# - 通过以太网发送位图,然后再返回(c# 和 c)

c - 需要帮助读取 C 中的文件

c函数调用错误