简体   繁体   English

分段错误将两个大数相加为字符串

[英]Segmentation fault adding two large numbers represented as strings

Here is the code snippet or rather a function which takes two strings as inputs which are basically large integers and prints the sum of them. 这是代码段,或者说是一个函数,该函数将两个字符串作为输入,它们基本上是大整数,并打印它们的总和。 I am getting the sum printed correctly, but a segmentation fault comes up at the end and I am unable to figure out its source. 我可以正确打印总和,但是最后出现分割错误,我无法弄清其来源。

string sum(string x, string y) {
    bool carry = false;
    int yLen = y.length(), xLen = x.length();
    vector<char> s;
    for(int i = xLen - 1, j = yLen - 1; i >= 0, j >= 0; i--, j--) {
        int a = x[i] - '0', b = y[j] - '0';
        int c = (carry?(a+b+1):(a+b));
        if(c/10)        carry = true, c %= 10;
        else            carry = false;
        s.push_back(c + '0');
    }
    for(int i = xLen - yLen - 1; i >= 0; i--) {
        int a = x[i] - '0';
        int c = (carry?(a+1):(a));
        if(c/10)        carry = true, c %= 10;
        else            carry = false;
        s.push_back(c + '0');
    }
    reverse(s.begin(), s.end());
    for(vector<char>::iterator i = s.begin(); i != s.end(); i++)        cout<<*i;
    cout<<endl;
}

Update: Assume that x.length() is always greater than or equal to y.length() in the input itself. 更新:假设x.length()在输入本身中始终大于或等于y.length()。

Your function returns string . 您的函数返回string

You need to return a string, or change that to void . 您需要返回一个字符串,或将其更改为void

void sum(string x, string y) {

Not returning in a value-returning function is undefined behaviour and is probably the cause of your segmentation fault. 不返回值返回函数是未定义的行为 ,可能是分段错误的原因。

This loop statement 此循环语句

for(int i = xLen - 1, j = yLen - 1; i >= 0, j >= 0; i--, j--) {

is already wrong. 已经错了。

The second expression in the loop 循环中的第二个表达式

i >= 0, j >= 0

is an expression of the comma operator. 是逗号运算符的表达式。 It does not take into account that i can be less than 0. The value of the expression is the value of the condition j >= 0. So if xLen is less than yLen then you will get that i will be equal to some negative number. 它不考虑i可以小于0。表达式的值是条件j> = 0的值。因此,如果xLen小于yLen,则将得到i等于某个负数。

You should rewrite this loop. 您应该重写此循环。 I think you meant expresssion 我想你的意思是表达

i >= 0 && j >= 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM