gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:02:37 25 4
gpt4 key购买 nike

根据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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com