Strtol函数cast的实现
我有自己的strtol实现,我认为它工作正常。情况如下:Strtol函数cast的实现,c,constants,C,Constants,我有自己的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(*
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;
}
为什么我必须将pos强制转换为(char),endPtr和pos都是指向char的指针,在其他情况下,警告会说:
赋值从整数生成指针而不强制转换。
感谢您的帮助
endPtr和pos都是指向char的指针
这是错误的<代码>pos定义为
const char *pos= nPtr;
和endPtr
as
char **endPtr
因为它们不是同一类型的
*endPtr
是char*
类型
pos
是const char*
类型。正如其他人指出的,因为const char*p
与char*p
不同
但是,如果将函数的签名更改为:
long strtol (const char * nPtr, const char ** endPtr, int base);
不需要强制转换。
*endPtr
=char*
,pos
=const char*
实际上不是同一类型。许多标准C库函数都有断开的签名。字符串文字类型为char*而不是const char*的副作用。修复该问题为时已晚。您的实现存在错误:char*endptr;strtol(“0x!”,和endptr,16);看跌期权(endptr)你会看到它打印“!”(正确的行为是打印“x!”)。另一个错误:long a=strtol(“xf”)和&endptr,16);printf(“%d”,a)代码>正确:0(未扫描数字)。错:15。@user2511527:如果你真的很开心,别忘了接受答案:)是的,更改*endPtr=pos后你是对的;这是正确的。
long strtol (const char * nPtr, const char ** endPtr, int base);