大佬们我这个为啥会在编译的时候 Segmentation Fault ,求求

P1303 A*B Problem

JunBuJian @ 2022-02-09 22:10:44

#include<iostream>
#include<vector>
#include<cstring>
#include<algorithm>

using namespace std;

vector<int> mul(vector<int> &A,vector<int> &B)
{
    vector<int> C;
    for(int i = 0;i < A.size();i ++)
    {
        int k = i;
        for(int j = 0;j < B.size();j ++)
        {
            C[k ++] += B[j] * A[i];
        }

    }

    for(int i = 0;i <= A.size()+B.size();i ++)
    {
        while(C[i] > 9) {
            C[i+1] += 1;
            C[i]%= 10;
        }
    }
    reverse (C.begin(),C.end());
    while(C.size() > 1 && C.back() == 0) C.pop_back();
    return C;
}
int main()
{
    string a,b;
    cin >> a >> b;

    vector<int> A,B;

    for(int i = a.size() - 1;i >= 0;i --) A.push_back(a[i] - '0');
    for(int i = b.size() - 1;i >= 0;i --) B.push_back(b[i] - '0');

    vector<int> C = mul(A,B);

    for(auto X:C) cout << X;
    return 0;
}

by rxjdasiwzl @ 2022-02-09 22:22:36

@JunBuJian 你 C 的大小初始为 0 啊。


by rxjdasiwzl @ 2022-02-09 22:23:07

要先 resize 给它大小才能访问下标不然越界


by Qing_fy @ 2022-02-09 22:23:24

段错误。

for(int j = 0;j < B.size();j ++)
{
            C[k ++] += B[j] * A[i];
}

C中容量为0,k++将访问到非法内存。


by JunBuJian @ 2022-02-09 22:47:15

已Ac,感谢大佬们


|