我想构建一个在C中加总大整数的程序。 所以我已经准备好了代码。程序使用mingw和Visual C ++编译器成功编译通过。但我的运行部分有问题。奇怪的是,当我在Visual Studio中调试程序时没有问题,但是当我运行它时,我的Windows显示该程序停止工作。 这是代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include "sum.h"
int isNumber(char* number)
{
int lenght = strlen(number);
int i,result = 0;
for (i = 0 ; i < lenght ; i++)
{
if (isdigit(*number++))
{
result = 1;
}
else
{
result = 0;
break;
}
}
return result;
}
int cti(char ch)
{
return ch - '0';
}
char* addZeros(char* number,int lenght)
{
int num_lenght = strlen(number),size = abs(lenght - num_lenght),i;
char* zeros = (char*)malloc(size);
strcpy(zeros,"");
zeros[size - 1] = '\0';
for (i = 0 ; i < abs(lenght - num_lenght) ; i++)
{
strcpy(&zeros[i],"0");
}
strncat(zeros,number,size);
number = (char*)malloc(sizeof(char)*size);
strncpy(number,zeros,size);
return number;
}
char* sum(char* numberOne,char* numberTwo)
{
if (numberOne == NULL || numberTwo == NULL)
return NULL;
if (!isNumber(numberOne) || !isNumber(numberTwo))
return NULL;
int CF = 0;
int lenghtOne = strlen(numberOne),lenghtTwo = strlen(numberTwo);
if (lenghtOne == 0 || lenghtTwo == 0)
return lenghtOne == 0 ? numberTwo : numberOne;
int max = lenghtOne > lenghtTwo? lenghtOne : lenghtTwo,index;
char* result = (char*)malloc(max);
int res = 0;
result[max] = '\0';
if (lenghtOne > lenghtTwo) numberTwo=addZeros(numberTwo,strlen(numberOne));
else if (lenghtOne < lenghtTwo) numberOne = addZeros(numberOne,strlen(numberTwo));
for ( index = max - 1 ; index >=0 ; index--)
{
res = cti(numberOne[index]) + cti(numberTwo[index]);
if (((res%10) + CF) > 9)
{
int num = ((res%10) + CF);
result[index] = (char)((int)'0'+num%10);
CF = num / 10;
}
else
{
result[index] = (char)((int)'0'+((res%10) + CF));
CF = res / 10;
}
}
return result;
}
int main(int argc, char *argv[])
{
char* num = "12345678";
char* num2= "2341";
char* result = sum(num,num2);
printf("%s\n",result);
return 0;
}
我认为问题出在指针的某处,但我并不完全确定。任何人都可以帮助我吗?
答案 0 :(得分:2)
您分配的内存量不足。它不包括用于终止字符串的空字符的空间,并且它不考虑诸如“9”+“1”之和的结果长度的变化。然后,您将在数组结束后写入空终止字符。
你应该像这样的长度使用malloc:
char* result = (char*)malloc(max + 2);
答案 1 :(得分:1)
result[max] = '\0';
这是不正确的,因为您只为结果分配了最大字符。我没有详细研究逻辑,但分配最多+ 1个字符可以解决这个特殊问题。