的
什么?
</强>
str = (uint8_t) malloc(len sizeof(uint8_t));
while (*str != ‘\0’)
</code>
这个
my_atoi()
代码没什么意义。代码分配内存未知的内存 - 然后立即尝试测试它们?
然后不需要内存分配
strlen()
不需要。
的
字符到十进制值
</强>
“我理解这部分会删除空字符:
a = str -‘0’;
“ - &gt;不完全。何时
str
是一个数字字符,
str -‘0’
将字符编码值(通常为ASCII)转换为其数值(如0到9)。
str -‘0’
不足以像十六进制数字
‘a’
,和
‘F’
。
的
替代
</强>
相反,迭代
ptr
并计算一个运行总和。
以下不符合2个编码目标,我将其留给OP作为子问题来处理。
**不应使用字符串函数或库。
**函数需要处理签名数据。
。
#include <ctype.h>
// Convert 1 digit
static int value(int ch) {
if (isdigit(ch)) {
return ch - ‘0’;
}
if (isxdigit(ch)) {
ch = tolower(ch);
const char *xdigits = “abcdef”;
return strchr(xdigits, ch) - xdigits + 10;
}
return INT_MAX; // non-digit
}
int32_t my_atoi(uint8_t ptr, uint8_t digits, uint32_t base) {
int32_t sum = 0;
while (ptr) {
sum = base;
sum += value(ptr++);
}
return sum;
}
</code>
更好的代码将检测非数字输入,溢出,无转换等。未显示的其他注意事项包括处理a
‘-‘
签名,验证范围内的基数。
int32_t my_atoi(uint8_t ptr, uint8_t digits, uint32_t base) {
int32_t sum = 0;
while (isspace(ptr)) ptr++; // skip leading white space
if (*ptr == ‘+’) ptr++; // Allow optional leading +
bool digit_found = false;
while (ptr) {
unsigned digit = value(ptr++);
if (digit >= base) {
return INT_MIN; // TBD signal unexpected digit
}
if (sum >= INT_MAX/base && (sum > INT_MAX/base || digit > INT_MAX%base)) {
// Overflow
return INT_MIN; // TBD signal OF
}
sum *= base;
sum += digit;
digit_found = true;
}
if (*str) {
sum = INT_MIN; // TBD signal unexpected junk at the end
}
if (!digit_found) {
sum = INT_MIN; // TBD signal no digits
}
return sum;
}
</code>
的
my_itoa()
</强>
寻求帮助
my_itoa()
,审查
实现良好的 itoa() 功能的正确方法是什么?
。它确实有一个很好的答案
-
</A>
某处。