在C中将数字添加为字符串

时间:2017-05-12 15:36:53

标签: c string pointers pointer-arithmetic

问题是,即使每次调用addnums函数时我都会增加指针,addnums数组只包含一个字符,最后一个字符是计算出来的。为什么会这样?

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

/* run this program using the console pauser or add your own getch,system("pause") or input loop */

int addHugeNumbers(char *a1, char *a2,char *res) ;
int checkifnum(char *c1) ;
void addnums(char *a1, char *a2, char *res, int *ip) ;

int main(int argc, char *argv[]) {

char firstnum[255],secondnum[255],addednum[255] = {0};

/*Óôçí ðåñßðôùóç ðïõ ï ÷ñÞóôçò äþóåé ôÝôïéïõò áñéèìïýò þóôå íá ÷ñåéáóôåß êáé    256 bit ôüôå åìöáíßæåé
ôïí ìÝãéóôï áñéèìü ðïõ ìðïñåß ìå 255 bit*/

printf("Give the first number : "); scanf("%s",&firstnum);
printf("Give the second number : "); scanf("%s",&secondnum);
printf("%s %s\n", firstnum,secondnum) ;
printf("%d",addHugeNumbers(firstnum,secondnum,addednum)) ;
return 0;
}

int addHugeNumbers(char *a1, char *a2,char *res){
int carry,len1,len2,*ip,i;
ip = &carry ;
if ((checkifnum(a1) == 0)||(checkifnum(a2) == 0)) return 0;
len1 = strlen(a1) - 1;
len2 = strlen(a2) - 1;
a1 += strlen(a1) - 1;
a2 += strlen(a2) - 1;
//printf("%c %c\n",*a1,*a2) ;
do{
    addnums(a1,a2,res,ip) ;
    len1--;len2--;   
    if (len1!=-1 && len2!=-1) a1--,a2--;
}while(len1>-1 && len2>-1) ;
printf("%s\n",res) ;
return 1;
}

void addnums(char *a1, char *a2, char *res, int *ip){
*res++ = (char)((*a1 - '0' + *a2 - '0' + *ip) % 10 + '0');
*ip = (*a1 - '0' + *a2 - '0' + *ip) / 10;
}

int checkifnum(char *c1){
while (*c1) {
    if (isdigit(*c1++) == 0) return 0;
}
return 1;   
}

1 个答案:

答案 0 :(得分:2)

您正在递增指针的本地副本,但不会将其传回。您需要reschar**并传递外部指针的地址,以便在addnums函数外部显示增量。