杭电ACM 1002为什么总是 Runtime Error(ACCESS_VIOLATION)?
发布网友
发布时间:2022-04-24 13:56
我来回答
共1个回答
热心网友
时间:2023-10-15 08:48
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
void addbig(char *a, char *b)
{
int ret;
int c = 0;
int lena = strlen(a);
int lenb = strlen(b);
int maxlen = (lena > lenb ? lena : lenb) + 1;
int len = maxlen;
char *sum = (char *) malloc(sizeof(maxlen + 1));
memset((void *)sum, '0', maxlen);
sum[maxlen--] = '\0';
lena--;
lenb--;
while (lena >= 0 && lenb >= 0)
{
ret = a[lena--] - '0' + b[lenb--] - '0' + c;
c = ret / 10;
ret %= 10;
sum[maxlen--] = ret + '0';
}
if (lena < 0)
{
while (lenb >= 0)
{
ret = b[lenb--] - '0' + c;
c = ret / 10;
ret %= 10;
sum[maxlen--] = ret + '0';
}
}
else if (lenb < 0)
{
while (lena >= 0)
{
ret = a[lena--] - '0' + c;
c = ret / 10;
ret %= 10;
sum[maxlen--] = ret + '0';
}
}
sum[maxlen] = c + '0';
for (int i = 0; i < len; ++i)
{
if (i == 0 && sum[i] == '0')
continue;
printf("%c", sum[i]);
}
printf("\n");
delete sum;//你忘了释放空间,导致多个样例使得动态开的空间不断增大,最后爆了,ps:你算的数组长度真的很精确,这是C++版本的释放空间,C版本目测用free,但是我不会,不好意思了。
}
int main()
{
int n;
scanf("%d", &n);
char a[1001];
char b[1001];
for (int i = 0; i < n; ++i)
{
scanf("%s%s", a, b);
printf("Case %d:\n", i + 1);
printf("%s + %s = ", a, b);
addbig(a, b);
if (i != n - 1)
printf("\n");
}
return 0;
}