Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hello, whenever I add and arrays that are not equal sizes, the program returns w

ID: 3651350 • Letter: H

Question

Hello, whenever I add and arrays that are not equal sizes, the program returns weird values which also contain the correct value in them. I understand that I have to pad the smaller array with 0's but I have no idea how to do that. Please help me :(

The assignment says:

In this assignment, you are going to use classes to create a new object type that can handle integers of any size (much larger than is allowed for an int).

Define a class called BigInt that represents an integer of any size
a. Store each digit of the number as a member of a dynamically allocated

array
b. Add constructors to:

Create an object with a string representing the value

Create a blank object of a given size

c. Make sure you have a destructor
d. Add a method to store a value into the object
e. Add a method to print out the value stored in the object

Add methods for addition, subtraction, multiplication, division

a. For example: the addition method will take another BigInt as a parameter, add this to the calling object and returns a pointer to new

BigInt object as the result

Explanation / Answer

The problem and the solution are actually really simple. Let's look at what's wrong:
Under BigINT::BigINT(string a):
data = new int[size];
This line of code does almost exactly what you want; it gives you a properly sized array to hold the digits. The only problem is that any time you allocate memory, whatever you get contains a whole bunch of what is called "garbage data". This is just whatever numbers were left over by the program that was using that piece of memory before you. When you go to store your numbers, you overwrite some of this garbage data, but the rest of the garbage is still there. This is why you're getting weird values -- your program is adding up this garbage data too.

The solution: Just set all the values to 0 before doing anything else
Look at the following:
data = new int[size];
for(int i = 0; i < size; i++)
data[i] = 0;
This will make sure that you are starting of with a completely clean array, rather than one filled with garbage data. Simple, right?