Search code examples
c++integermultiplication

Why does function call go directly to return statement?


I am a BEGINNER. I wrote a function to multiply big integers. When the function multiplybig(string a,string b) is called it goes directly to the return statement of the same function. I dont know where exactly the bug is. can someone please help me with this?

#include<iostream>
#include<string>
using namespace std;
string multiplybig(string a,string b)
{
    string c;
    int ar1[a.length()] , ar2[b.length()] ; int ans[a.length()+b.length()]={0};

    for(int i=0 ; i<a.length(); i++){
        ar1[i]=a[i]-'0';
    }

    for(int i = 0 ; i<a.length(); i++){
        ar2[i]=b[i]-'0';
    }

    int x = 0 ; int y = 0;

    for(int i=a.length()-1;i>=0;i--) {
        for(int j=b.length()-1;j>=0;j--){
            ans[x]+=ar1[i]*ar2[j];
            x++;
        }
        y++; x=y;
    }

    for(int i=0,j=a.length()+b.length()-1;i<a.length()+b.length();i++,j--){
        c[i]=ans[j]+'0';
    }

    return c;
}
int main()
{
    string a( "123" );
    string b( "111" );
    cout<< multiplybig( a, b );
    return 0;
}

Solution

  • To sum up the comments:

    Don't use VLAs

    int ar1[a.length()] , ar2[b.length()] ; int ans[a.length()+b.length()]={0};
    

    are VLAa. Those are not part of the standard, but a compiler specific extension. The right way would be to use std::vector:

    std::vector<int> ar1(a.length());
    std::vector<int> ar2(b.length()); 
    std::vector<int> ans(a.length() + b.length());
    

    (one statement per line for good readability)

    Typo in the loop

    for(int i = 0 ; i<a.length(); i++){
        ar2[i]=b[i]-'0';
    }
    

    Since you read from b the condition must be i < b.length();

    Out-of-bounds-access on c[i]

    Before the line

    c[i]=ans[j]+'0';
    

    c get's never assigned anything (it's an empty string), so any access using the subscript operator is an out-of-bounds-access. Either resize it first:

    c.resize(ans.size());
    

    or use push_back instead:

    c.push_back(ans[j]+'0');
    

    The last error (that the returned value was ignored) you already fixed in your last edit. With all those changed I got the expected result

    013653