C使用char[]的减法

C a subtract method with char[]

本文关键字:使用 char      更新时间:2023-10-16

我试图实现减法方法,但发现有一些错误。

55-44是正确的555-44不正确,将返回011100-44将导致分段故障

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <sstream>
char* subtract(char *n1,char *n2){
    int n1Len = strlen(n1);
    int n2Len = strlen(n2);

    int diff;  
    int max=n1Len;
    char* res = (char*)malloc (max+2);
    memset(res, '0', max +1); 
    res[max] = '';
    int i=n1Len - 1, j = n2Len - 1, k = max;
    for (; i >= 0 && j >=0; --i, --j, --k) {
        if(i >= 0 && j>=0)
        {
            diff = (n1[i] - '0') - (n2[j] - '0');
            if(diff<0)
            {
                int temp=n1[i-1]-'0';
                temp=temp-1;
                n1[i-1]=temp+'0';
                diff+=10;
            }
            res[i]=diff+'0';
        }
        else 
            res[i]=n1[i];
    }
    return res;
}

int main(void) {
    printf("%sn",  subtract("100","44"));
}

我在GMP中写它只是为了好玩。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <gmp.h>
char* subtract(char *n1,char *n2){
  mpz_t n1z, n2z;
  char * res = malloc(strlen(n1) > strlen(n2) ? strlen(n1) + 1 : strlen(n2) + 1);
  mpz_init_set_str(n1z, n1, 10);
  mpz_init_set_str(n2z, n2, 10);
  mpz_sub(n2z, n1z, n2z);
  gmp_sprintf(res, "%Zd", n2z);
  mpz_clear(n1z);
  mpz_clear(n2z);
  return res; 
}
int main(void) {
  printf("%sn",  subtract("55","44"));
  printf("%sn",  subtract("555","44"));
  printf("%sn",  subtract("100","44")); 
}

555-44不起作用的原因是您在'for'语句中测试的条件与在'if'语句中相同。如果一个字符串比另一个字符串长,则会导致循环提前退出。

100-44导致分段错误的原因是您正试图写回一个常量字符串。

您的借款逻辑也不考虑从"0"借款。

只有怎么样

int i1 = atoi(n1);
int i2 = atoi(n2);
int result = i1 - i2; 
char * retval = malloc(2*strlen(n1)); // Easier than figuring out exact right size!
sprintf(retval, "%d", result);
return retval;

那不是更好吗?