我正在尝试组合一个程序,这个程序总和非常大。不幸的是,我被卡住了 - 它不会返回任何结果,即使我注释掉了malloc & realloc(编译器似乎失败了)。有任何想法吗?我的代码:如何总结大数字
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int i,j,x;
char *actual = NULL;
char *sum = NULL;
void init() {
sum = malloc(500);
actual = malloc(500);
}
void calculate (char *argv[]) {
int rest = 0;
actual = *argv;
actual = realloc(actual, strlen(*argv));
if (strlen(actual) > strlen(sum)) {
sum = realloc(sum, strlen(actual) + 1);
} else sum = realloc(sum, strlen(sum) + 1);
long b;
for (b = 1; b < strlen(actual); b++) {
rest = rest + atoi(&sum[strlen(sum) - b]) + atoi(&actual[strlen(actual) - b]);
if (rest > 9) {
sum[strlen(sum) - b] = rest - 10;
rest = 1; // carrying over 1
} else {
sum[strlen(sum) - b] = rest;
rest = 0;
}
}
}
void writeResult() {
printf("VYPIS - sum:");
printf("strlen souctu je: %lu\n",strlen(sum));
long c;
for (c = 0; c <= strlen(sum); c++) {
printf("%c",sum[c]);
}
printf("\n");
}
void emtpy() {
free(actual);
free(sum);
}
int main(int argc, char * argv[]) {
init();
for (i = 1; i < argc; i++) {
calculate(&argv[i]);
}
writeResult();
emtpy();
return 0;
}
经常检查可能会遇到错误函数的结果! – Olaf
每次调用strlen()并确保传递一个有效的以NULL结尾的字符串。 –
注意:'atoi'需要一个以null结束的字符串,这不是:'atoi(&sum [strlen(sum) - b])''。要转换一个数字,你可以做'x''0'。 – szczurcio