马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
char *append_result(char *result, char ch)
{
char *last = result;
int limit = 0;
int times = 1;
// 定位到字符串的末尾
while(last[limit++] != '\0')
{
if(limit >= INCREMENT)
{
limit = 0;
times++;
last += INCREMENT;
}
}
last[limit - 1] = 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[limit] = '\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'; // 需要 '\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[limit++] != '\0')
{
if(limit >= INCREMENT)
{
limit = 0;
times++;
last += INCREMENT;
}
}
|