【发布时间】:2013-06-22 13:26:14
【问题描述】:
我有自己的 strtol 实现,我认为它可以正常工作。如下所示:
long strtol(const char *nPtr, char **endPtr, int base)
{
const char *start;
int number;
long int sum = 0;
int sign = 1;
const char *pos = nPtr;
if (*pos == '\0')
return 0;
start = pos;
while (isspace(*pos))
{
++pos;
}
if (*pos == '-')
{
sign = -1;
++pos;
}
if (*pos == '+')
++pos;
if (base == 16 || base == 8)
{
if (base == 16 && *pos == '0')
++pos;
if (base == 16 && (*pos == 'x' || *pos == 'X'))
++pos;
if (base == 8 && *pos == '0')
++pos;
}
if (base == 0)
{
base = 10;
if (*pos == '0')
{
base = 8;
++pos;
if (*pos == 'x' || *pos == 'X')
{
base = 16;
++pos;
}
}
}
if ((base < 2 || base > 36) && base != 0)
{
errno = EINVAL;
return 0;
}
while (*pos != '\0')
{
number = -1;
if ((int) *pos >= 48 && (int) *pos <= 57)
{
number = (int) *pos - 48;
}
if (isalpha(*pos))
{
number = (int) toupper(*pos) - 55;
}
if (number < base && number != -1)
{
if (sign == -1)
{
if (sum >= ((LONG_MIN + number) / base))
sum = sum * base - number;
else
{
errno = ERANGE;
sum = LONG_MIN;
}
}
else
{
if (sum <= ((LONG_MAX - number) / base))
sum = sum * base + number;
else
{
errno = ERANGE;
sum = LONG_MAX;
}
}
}
else if (base == 16 && number > base
&& (*(pos - 1) == 'x' || *(pos - 1) == 'X'))
{
--pos;
break;
}
else
break;
++pos;
}
if (!isdigit(*(pos - 1)) && !isalpha(*(pos - 1)))
pos = start;
if (endPtr)
*endPtr = (char*) pos;
return sum;
}
但是我对最后一行有疑问:
*endPtr = (char*)pos;
为什么我必须将 pos 转换为 (char),endPtr 和 pos 都是指向 char 的指针,否则警告会说: 赋值使指针从整数而不进行强制转换。 感谢帮助
【问题讨论】:
-
*endPtr=char*,pos=const char*真的不是同一类型。 -
许多标准 C 库函数的签名已损坏。字符串文字类型为 char* 而不是 const char* 的副作用。解决这个问题为时已晚。
-
您的实现有一个错误:
char *endptr; strtol("0x!", &endptr, 16); puts(endptr);,您会看到它打印出“!” (正确的行为是打印“x!”)。 -
另一个错误:
long a = strtol(" xf", &endptr, 16); printf("%d", a);正确:0(未扫描数字)。错误:15。