Question

I tried to subtract two large positive integers with the help of arrays. But when running the code below I get a segmentation fault (core dumped) when run on g++ (Ubuntu).

I followed Subtract numbers using arrays - C++ and Subtracting two long positive integers in an array c++ but couldn't find much of help from these.

int main() {
vector <int> N;
vector <int> a;
vector <int> y;
char digit1;
int l;

do {
    cin.get(digit1);
    if (digit1 != (int)
        '\n')
        N.push_back(int(digit1) - int('0'));
} while (digit1 != (int)
    '\n');

char digit2;
do {
    cin.get(digit2);
    if (digit2 != (int)
        '\n')
        a.push_back(int(digit2) - int('0'));
} while (digit2 != (int)
    '\n');

int i = N.size() - 1;
int j = a.size() - 1;
int k = 0;
do {
    if (j >= 0) {
        if (N[i] < a[j]) {
            y[k] = N[i] + 10 - a[j];
            l = i - 1;
            while (N[l] == 0) {
                N[l] = 9;
                l--;
            }
            N[l] = N[l] - 1;
        } else {
            y[k] = N[i] - a[j];
        }
        i--;
        j--;
        k++;
    } else {
        y[k] = N[i];
        i++;
        k++;
    }
} while (i >= 0);

for (int m = y.size() - 1; m >= 0; m--) {
    cout << y[m];
}
return 0;
Was it helpful?

Solution

Your y vector is never allocated any space before you use operator[] to dereference its elements. Specifically this:

y[k] = N[i] - a[j];

Pretty sure you want to push_back() that, or preallocate the space. Either way, dereferencing even the zero-index of a zero-sized vector isn't good.

OTHER TIPS

Allocate space for vector y

vector<int> y(n,0); //n = max of N.size() & a.size()

else {
    y[k] = N[i];
    i++; // Should be i--
    k++;

}

Have you included vector?

Also, please give us compiler output.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top