Hello world!
I have an overloaded operator+, which behaves a bit strange. It workes flawlessly when chaining two operations at most, but gives a runtime error, when chaining more than two operations. I could not find and answer to why this is happening. Could anyone please explain to me what am I doing wrong? I have a feeling, that my problem is maybe related to const-correctness, but could not find an article, which would have explained why am I getting this error...
Some additional information, to make things clearer: this is an assignment, where I must implement 'big numbers' with addition and multiplication. I must represent big numbers as a sequence of digits.
overloaded operator+:
Code:
NagyonNagySzam operator+(NagyonNagySzam a, NagyonNagySzam b ){
//DEKLARÁCIÓK, INICIALIZÁCIÓ
NagyonNagySzam eredmeny;
NagyonNagySzam* hosszabb;
NagyonNagySzam* rovidebb;
if(a.hossz>b.hossz){
hosszabb=&a;
rovidebb=&b;
}else{
hosszabb=&b;
rovidebb=&a;
}
eredmeny.hossz=hosszabb->hossz + 1;
eredmeny.szamjegyek=new int[ eredmeny.hossz ];
//ALGORITMUS
eredmeny.szamjegyek[0]=(rovidebb->szamjegyek[0] + hosszabb->szamjegyek[0])%10;
int atvitel=(rovidebb->szamjegyek[0] + hosszabb->szamjegyek[0])/10;
for(int i=1;i<=hosszabb->hossz;++i){
if(i<rovidebb->hossz){
eredmeny.szamjegyek[i]=(rovidebb->szamjegyek[i] + hosszabb->szamjegyek[i] + atvitel)%10;
atvitel=(rovidebb->szamjegyek[i] + hosszabb->szamjegyek[i] + atvitel)/10;
}else if(i<hosszabb->hossz){
eredmeny.szamjegyek[i]=(hosszabb->szamjegyek[i] + atvitel)%10;
atvitel=(hosszabb->szamjegyek[i] + atvitel)/10;
}else{
if(atvitel==0){
eredmeny.hossz=eredmeny.hossz - 1;
}else{
eredmeny.szamjegyek[i]=atvitel;
atvitel=0;
}
}
}
return eredmeny;
}
Some hints to the code above: first, I check which 'big number' is longer, then i assign a pointer to the longer and the shorter ones accordingly. Then, I do an addition just like I would do on paper.
main.cpp with everything allright:
Code:
#include "nagyonnagy.h"
#include <iostream>
#include <string>
int main(){
NagyonNagySzam a("100");
NagyonNagySzam b("20");
NagyonNagySzam c("3");
NagyonNagySzam x("123");
NagyonNagySzam d=x+x+b;
std::cout<<d<<std::endl;
return 0;
}
main.cpp with runtime error:
Code:
#include "nagyonnagy.h"
#include <iostream>
#include <string>
int main(){
NagyonNagySzam a("100");
NagyonNagySzam b("20");
NagyonNagySzam c("3");
NagyonNagySzam x("123");
NagyonNagySzam d=x+x+b+a;
std::cout<<d<<std::endl;
return 0;
}
Um... I don't know what else should I say. I would be glad if someone could help me, 'cause I have used all my last chances with this assignment. :/ Thanks in advance!