求助
char *append_result(char *result, char ch){
char *last = result;
int limit = 0;
int times = 1;
// 定位到字符串的末尾
while(last != '\0')
{
if(limit >= INCREMENT)
{
limit = 0;
times++;
last += INCREMENT;
}
}
last = ch;
if(limit >= INCREMENT)
{
int offset = last - result;
result = (char *)realloc(result, INIT_SIZE + INCREMENT * times);
last = result;
last += offset;
last += INCREMENT;
limit = 0; // reset
}
last = '\0';
return result;
}
// 将两个字符串对应的数值相加
char *add_two_strs(char *str1, char *str2)
{
int carry = 0; // 存放进位
int num1, num2, num3;
char *result;
result = (char *)malloc(INIT_SIZE);
if(result == NULL)
{
exit(1);
}
result = '\0'; // 需要 '\0'
// 字符串的存放顺序跟加法规则相反
// 需要先反转字符串
str1 = reverse_str(str1);
str2 = reverse_str(str2);
// 两个字符串按位相加
while(*str1 != '\0' || *str2 != '\0')
{
num1 = *str1 - '0';
num2 = *str2 - '0';
if(*str1 == '\0')
{
num1 = 0;
}
else
{
str1++;
}
if(*str2 == '\0')
{
num2 = 0;
}
else
{
str2++;
}
num3 = num1 + num2 + carry;
if(num3 > 9)
{
result = append_result(result, num3 - 10 + '0');
carry = 1;
}
else
{
result = append_result(result, num3 + '0');
carry = 0;
}
}
if(carry)
{
append_result(result, carry + '0');
}
result = reverse_str(result);
return result;
}
int main(void)
{
char *num1;
char *num2;
char *result;
num1 = get_num();//该函数将输入的数字以字符类型传入指针数组
num2 = get_num();
result = add_two_strs(num1, num2);
printf("计算结果是:%s\n", result);
return 0;
}
这段代码我想问一下是怎么实现定位到字符串末尾的,result指针定义之后也没有赋值,那last【limit】又有什么意义呢
// 定位到字符串的末尾
while(last != '\0')
{
if(limit >= INCREMENT)
{
limit = 0;
times++;
last += INCREMENT;
}
} {:10_280:}看不懂啊 本帖最后由 两手空空儿 于 2023-1-3 16:45 编辑
// 定位到字符串的末尾
while(last != '\0') //找到\0的位置就是末尾了,只不过它记录位置的方法是通过 INCRMENT * time + limit 的方式
{
if(limit >= INCREMENT)
{
limit = 0;
times++;
last += INCREMENT;
}
}
if(limit >= INCREMENT)
{
int offset = last - result;
result = (char *)realloc(result, INIT_SIZE + INCREMENT * times);
//这里用的是realloc,result被重新分配内存以后,原来的内容会被复制到新的内存单元中,所以这里result指向的内容和原来的内容是一样的,
// last修改的内容就是result指向的内容
last = result;
last += offset;
last += INCREMENT;
limit = 0; // reset
}
last = '\0';
页:
[1]