I am trying to implement the digitwise addition of unsigned ints, given by user input, with carryover and arrays. This is the general idea of the below code:
- receive a,b from user input and allocate memory for 2 arrays for each digit/char in a, b
- allocate memory for an array that can contain the max amount of digits of a,b + 1 in case of carryover into first digit
- populate both arrays with for loops (i think my numbers will be flipped, since strings start from the left iirc - but thats the least of my problems and easily fixable once I can actually test it)
- add the elements of the arrays containing the digits of a,b one by one + previous carryover and determine whether that addition caused carryover. Once the smaller of the two arrays is exceeded, populate only with elements of the larger one and add potential carryover once in the first step.
- print out the elements of the array containing the digits of the sum.
I left out some details and this is only like 90ish% finished, but the general logic should be fine after double-checking and a few tests. Though, I am running into memory issues left and right, regardless of all the adjustments i made thus far [Segmentation fault (core dumped) regardless of input]. I can't even attempt to debug with cout's etc. since it doesn't even output a cout placed anywhere in the entire program.
As you can tell I am new to C++ and would appreciate advice on how to fix this.
#include <iostream>
using namespace std;
int main(){
string a, b;
unsigned int carryover;
unsigned int i;
cout<<"Natürliche Zahl a"<<endl;
cin>>a;
cout<<"Natürliche Zahl b"<<endl;
cin>>b;
unsigned int *arr_a = (unsigned int*) malloc((a.length()-1)*sizeof(unsigned int));
unsigned int *arr_b = (unsigned int*) malloc((b.length()-1)*sizeof(unsigned int));
unsigned int *arr_sum = (unsigned int*) malloc(max(a.length(),b.length())*sizeof(unsigned int));
for(i = 0; i < a.length()-1; i++){
arr_a[i] = stoi(a.substr(i,1));
}
for(i = 0; i < b.length()-1; i++){
arr_b[i] = stoi(b.substr(i,1));
}
carryover = 0;
for(i = 0; i < max(a.length(),b.length())-1; i++){
if(i < a.length()-1 && i < b.length()-1){
arr_sum[i] = (arr_a[0]+arr_b[0])%(10^i) + carryover;
carryover = (arr_a[0] + arr_b[0] + carryover)/(10^i);
}
else if(i >= a.length()-1){
arr_sum[i] = arr_b[i] + carryover;
carryover = 0;
}
else{
arr_sum[i] = arr_a[i] + carryover;
carryover = 0;
}
arr_sum[max(a.length(),b.length())] = carryover;
}
for(i = max(a.length(),b.length()); i >= 0; i--){
cout<<arr_sum[i];
}
free(arr_a);
free(arr_b);
free(arr_sum);
return 0;
}