-1

So I am trying to code for this question:

Yes, I have to use arrays since it is a requirement.

Consider the problem of adding two n-bit binary integers, stored in two n-element arrays A and B. The sum of the two integers should be stored in binary form in an (n+1) element array C . State the problem formally and write pseudocode for adding the two integers.

I know that the ans array contains the correct output at the end of the addd function. However, I am not able to output that answer.

Below is my code. Please help me figure where in the code I'm going wrong, and what I can do to change it so it works. I will be very grateful.

#include <iostream>
using namespace std;

int * addd(int a[], int n1, int b[], int n2)
{
    int s;
    if(n1<n2) {s=n2+1;}
    else {s=n1+1;}
    int ans[s];
    int i=n1-1, j=n2-1, k=s-1;
    int carry=0;
    while(i>=0 && j>=0 && k>0)
    {
        ans[k]=(a[i]+b[j]+carry)%2;
        //cout<<k<<" "<<ans[k]<<endl;
        carry=(a[i]+b[j]+carry)/2;
        i--; j--; k--;
    }
    //cout<<"Carry "<<carry<<endl;
    ans[0]=carry;
    return ans;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    int a[]={0,0,0,1,1,1};
    int n1=sizeof(a)/sizeof(a[0]);
    int b[]={1,0,1,1,0,1};
    int n2=sizeof(b)/sizeof(b[0]);
    int *p=addd(a,6,b,6);
//    cout<<p[1]<<endl;
//    cout<<p[0]<<" "<<p[1]<<" "<<p[2]<<" "<<p[3]<<" "<<p[4]<<" "<<p[5]<<" "<<p[6]<<endl;
    return 0;
}
E_net4
  • 27,810
  • 13
  • 101
  • 139
Unyaya
  • 68
  • 7

4 Answers4

1

If You Must Only Use C Arrays

Returning ans is returning the pointer to a local variable. The object the pointer refers to is no longer valid after then function has returned, so trying to read it would lead to undefined behavior.

One way to fix this is to pass in the address to an array to hold your answer, and populate that, instead of using a VLA (which is a non-standard C++ extension).

A VLA (variable length array) is an array which takes its size from a run-time computed value. In your case:

int s;
//... code that initializes s
int ans[s];

ans is a VLA because you are not using a constant to determine the array size. However, that is not a standard feature of the C++ language (it is an optional one in the C language).

You can modify your function so that ans is actually provided by the caller.

int * addd(int a[], int n1, int b[], int n2, int ans[])
{
    //...

And then the caller would be responsible for passing in a large enough array to hold the answer.

Your function also appears to be incomplete.

    while(i>=0 && j>=0 && k>0)
    {
        ans[k]=(a[i]+b[j]+carry)%2;
        //cout<<k<<" "<<ans[k]<<endl;
        carry=(a[i]+b[j]+carry)/2;
        i--; j--; k--;
    }

If one array is shorter than the other, then the index for the shorter array will reach 0 first. Then, when that corresponding index goes negative, the loop will stop, without handling the remaining terms in the longer array. This essentially makes the corresponding entries in ans be uninitialized. Reading those values results in undefined behavior.

To address this, you should populate the remaining entries in ans with the correct calculation based on carry and the remaining entries in the longer array.


A More C++ Approach

The original answer above was provided assuming you were constrained to only using C style arrays for both input and output, and that you wanted an answer that would allow you to stay close to your original implementation.

Below is a more C++ oriented solution, assuming you still need to provide C arrays as input, but otherwise no other constraint.

C Array Wrapper

A C array does not provide the amenities that you may be accustomed to have when using C++ containers. To gain some of these nice to have features, you can write an adapter that allows a C array to behave like a C++ container.

template <typename T, std::size_t N>
struct c_array_ref {
    typedef T ARR_TYPE[N];
    ARR_TYPE &arr_;

    typedef T * iterator;
    typedef std::reverse_iterator<T *> reverse_iterator;

    c_array_ref (T (&arr)[N]) : arr_(arr) {}

    std::size_t size () { return N; }

    T & operator [] (int i) { return arr_[i]; }
    operator ARR_TYPE & () { return arr_; }

    iterator begin () { return &arr_[0]; }
    iterator end () { return begin() + N; }

    reverse_iterator rbegin () { return reverse_iterator(end()); }
    reverse_iterator rend () { return reverse_iterator(begin()); }
};
Use C Array References

Instead of passing in two arguments as information about the array, you can pass in the array by reference, and use template argument deduction to deduce the array size.

Return a std::array

Although you cannot return a local C array like you attempted in your question, you can return an array that is wrapped inside a struct or class. That is precisely what the convenience container std::array provides. When you use C array references and template argument deduction to obtain the array size, you can now compute at compile time the proper array size that std::array should have for the return value.

template <std::size_t N1, std::size_t N2>
std::array<int, ((N1 < N2) ? N2 : N1) + 1>
addd(int (&a)[N1], int (&b)[N2])
{
Normalize the Input

It is much easier to solve the problem if you assume the arguments have been arranged in a particular order. If you always want the second argument to be the larger array, you can do that with a simple recursive call. This is perfectly safe, since we know the recursion will happen at most once.

    if (N2 < N1) return addd(b, a);
Use C++ Containers (or Look-Alike Adapters)

We can now convert our arguments to the adapter shown earlier, and also create a std::array to hold the output.

    c_array_ref<int, N1> aa(a);
    c_array_ref<int, N2> bb(b);
    std::array<int, std::max(N1, N2)+1> ans;
Leverage Existing Algorithms if Possible

In order to deal with the short comings of your original program, you can adjust your implementation a bit in an attempt to remove special cases. One way to do that is to store the result of adding the longer array to 0 and storing it into the output. However, this can mostly be accomplished with a simple call to std::copy.

    ans[0] = 0;
    std::copy(bb.begin(), bb.end(), ans.begin() + 1);

Since we know the input consists of only 1s and 0s, we can compute straight addition from the shorter array into the longer array, without concern for carry (that will be addressed in the next step). To compute this addition, we apply std::transform with a lambda expression.

    std::transform(aa.rbegin(), aa.rend(), ans.rbegin(),
                   ans.rbegin(),
                   [](int a, int b) -> int { return a + b; });

Lastly, we can make a pass over the output array to fix up the carry computation. After doing so, we are ready to return the result. The return is possible because we are using std::array to represent the answer.

    for (auto i = ans.rbegin(); i != ans.rend()-1; ++i) {
        *(i+1) += *i / 2;
        *i %= 2;
    }

    return ans;
}
A Simpler main Function

We now only need to pass in the two arrays to the addd function, since template type deduction will discover the sizes of the arrays. In addition, the output generator can be handled more easily with an ostream_iterator.

int main(int, const char * []) {
    int a[]={1,0,0,0,1,1,1};
    int b[]={1,0,1,1,0,1};
    auto p=addd(a,b);
    
    std::copy(p.begin(), p.end(),
              std::ostream_iterator<int>(std::cout, " "));

    return 0;
}

Try it online!

jxh
  • 69,070
  • 8
  • 110
  • 193
  • What do you mean by "Instead, pass in the address to an array to hold your answer, and populate that, instead of using a VLA (which is a non-standard C++ extension)" – Unyaya Nov 18 '20 at 23:00
  • Answer has been updated. Good luck on your assignment! – jxh Nov 18 '20 at 23:17
  • I love your explanation. Your explanation has made it crystal clear as to why (the underlying concept) the code doesn't work and for that I'm very very grateful. Thank you so much – Unyaya Nov 19 '20 at 05:58
1
using namespace std;

Don't write using namespace std;. I have a summary I paste in from a file of common issues when I'm active in the Code Review Stack Exchange, but I don't have that here. Instead, you should just declare the symbols you need, like using std::cout;

int * addd(int a[], int n1, int b[], int n2)

The parameters of the form int a[] are very odd. This comes from C and is actually transformed into int* a and is not passing the array per-se.

The inputs should be const.

The names are not clear, but I'm guessing that n1 is the size of the array? In the Standard Guidelines, you'll see that passing a pointer plus length is strongly discouraged. The Standard Guidelines Library supplies a simple span type to use for this instead.

And the length should be size_t not int.

Based on the description, I think each element is only one bit, right? So why are the arrays of type int? I'd use bool or perhaps int8_t as being easier to work with.

What are you returning? If a and b and their lengths are the input, where is the output that you are returning a pointer to the beginning of? This is not giving value semantics, as you are returning a pointer to something that must exist elsewhere so what is its lifetime?

    int s;
    int ans[s];

    return ans;

Well, there's your problem. First of all, declaring an array of a size that's not a constant is not even legal. (This is a gnu extension that implements C's VLA feature but not without issues as it breaks the C++ type system) Regardless of that, you are returning a pointer to the first element of the local array, so what happens to the memory when the function returns? Boom.

    int s;

No. Initialize values when they are created.

    if(n1<n2) {s=n2+1;}
    else {s=n1+1;}

Learn the library. How about:

const size_t s = 1+std::max(n1,n2);

and then the portable way to get your memory is:

std::vector<int> ans(s);

Your main logic will not work if one array is shorter than the other. The shorter input should behave as if it had leading zeros to match. Consider abstracting the problem of "getting the next bit" so you don't duplicate the code for handling each input and make an unreadable mess. You really should have learned to use collections and iterators first.

now:

    return ans;

would work as intended since it is a value. You just need to declare the function to be the right type. So just use auto for the return type and it knows.

    int n1=sizeof(a)/sizeof(a[0]);

Noooooooo.

There is a standard function to give the size of a built-in primitive array. But really, this should be done automatically as part of the passing, not as a separate thing, as noted earlier.

    int *p=addd(a,6,b,6);

You wrote 6 instead of n1 etc. Anyway, with the previous edits, it becomes:

using std::size;
const auto p = addd (a, size(a), b, size(b));

Finally, concerning:

   cout<<p[0]<<" "<<p[1]<<" "<<p[2]<<" "<<p[3]<<" "<<p[4]<<" "<<p[5]<<" "<<p[6]<<endl;

How about using loops?

for (auto val : p)  cout << val;
cout << '\n';

oh, don't use endl. It's not needed for cout which auto-flushes anyway, and it's slow. Modern best practice is to use '\n' and then flush explicitly if/when needed (like, never).

JDługosz
  • 5,592
  • 3
  • 24
  • 45
1

Let's look at:

 int ans[s];

Apart that this is not even part of the standard and probably the compiler is giving you some warnings (see link), that command allocate temporary memory in the stack which gets deallocated on function exit: that's why you are getting every time different results, you are reading garbage, i.e. memory that in the meantime might have been overwritten. You can replace it for example with

 int* ans = new int[s];

Don't forget though to deallocate the memory when you have finished using the buffer (outside the function), to avoid memory leakage.


Some other notes:

    int s;
    if(n1<n2) {s=n2+1;}
    else {s=n1+1;}

This can be more elegantly written as:

    const int s = (n1 < n2) ? n2 + 1 : n1 + 1;

Also, the actual computation code is imprecise as it leads to wrong results if n1 is not equal to n2: You need further code to finish processing the remaining bits of the longest array. By the way you don't need to check on k > 0 because of the way you have defined s. The following should work:

    int i=n1-1, j=n2-1, k=s-1;
    int carry=0;
    while(i>=0 && j>=0)
    {
        ans[k]=(a[i]+b[j]+carry)%2;
        carry=(a[i]+b[j]+carry)/2;
        i--; j--; k--;
    }
    while(i>=0) {
        ans[k]=(a[i]+carry)%2;
        carry=(a[i]+carry)/2;
        i--; k--;
    }
    while(j>=0) {
        ans[k]=(b[j]+carry)%2;
        carry=(b[j]+carry)/2;
        j--; k--;
    }
    ans[0]=carry;
    return ans;
}
Antonio
  • 19,451
  • 13
  • 99
  • 197
  • 1
    Thank you so much for your response!! I was actually waiting for the output of this code to work so that I could work on the instances when the length of the two arrays isn't the same. Your answer of using int* ans = new int[s]; is what I was looking for so thank you very much! – Unyaya Nov 19 '20 at 05:54
  • Using `new` is actually a very poor design. The [Core Guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines) repeatedly admonishes, "No Naked New". This logic code repeats the identical block 3 times, which is poor. "more elegantly written..." is true enough but neglects the Standard Algorithm that already exists. – JDługosz Nov 19 '20 at 13:56
  • @JDlugosz The problem statement required the use of an allocated buffer. The right thing would have been to use a std::vector. For the rest, if you are referring to std::max, it happens to be utterly inefficient in some platforms – Antonio Nov 19 '20 at 22:45
  • I would think that `std::max` would use whatever careful phasing and/or compiler hints are needed to ensure generating the best code; e.g. a conditional move instruction. How does writing the same logic directly do better? – JDługosz Jan 19 '21 at 16:31
0

If I may editorialize a bit... I think this is a deceptively difficult question for beginners, and as-stated should flag problems in the design review long before any attempt at coding. It's telling you to do things that are not good/typical/idiomatic/proper in C++, and distracting you with issues that get in the way of the actual logic to be developed.

Consider the core algorithm you wrote (and Antonio corrected): that can be understood and discussed without worrying about just how A and B are actually passed in for this code to use, or exactly what kind of collection it is. If they were std::vector, std::array, or primitive C array, the usage would be identical. Likewise, how does one return the result out of the code? You populate ans here, and how it is gotten into and/or out of the code and back to main is not relevant.

Primitive C arrays are not first-class objects in C++ and there are special rules (inherited from C) on how they are passed as arguments.

Returning is even worse, and returning dynamic-sized things was a major headache in C and memory management like this is a major source of bugs and security flaws. What we want is value semantics.

Second, using arrays and subscripts is not idiomatic in C++. You use iterators and abstract over the exact nature of the collection. If you were interested in writing super-efficent back-end code that doesn't itself deal with memory management (it's called by other code that deals with the actual collections involved) it would look like std::merge which is a venerable function that dates back to the early 90's.

template< class InputIt1, class InputIt2, class OutputIt >
OutputIt merge( InputIt1 first1, InputIt1 last1,
                InputIt2 first2, InputIt2 last2,
                OutputIt d_first );

You can find others with similar signatures, that take two different ranges for input and outputs to a third area. If you write addp exactly like this, you could call it with primitive C arrays of hardcoded size:

int8_t A[] {0,0,0,1,1,1};
int8_t B[] {1,0,1,1,0,1};
int8_t C[ ??? ];

using std::begin; std::end;

addp (begin(A),end(A), begin(B), end(B),  begin(C));

Note that it's up to the caller to have prepared an output area large enough, and there's no error checking.

However, the same code can be used with vectors, or even any combination of different container types. This could populate a std::vector as the result by passing an insertion iterator. But in this particular algorithm that's difficult since you're computing it in reverse order.

std::array

Improving upon the situation with primitive C arrays, you could use the std::array class which is exactly the same array but without the strange passing/returning rules. It's actually just a primitive C array inside a wrapping struct. See this documentation: https://en.cppreference.com/w/cpp/container/array

So you could write it as:

using BBBNum1 = std::array<int8_t, 6>
BBBNum1 addp (const BBBNum1& A, const BBBNum1& B) { ... }

The code inside can use A[i] etc. in the same way you are, but it also can get the size via A.size(). The issue here is that the inputs are the same length, and the output is the same as well (not 1 larger). Using templates, it could be written to make the lengths flexible but still only specified at compile time.

std::vector

The vector is like an array but with a run-time length. It's dynamic, and the go-to collection you should reach for in C++.

using BBBNum2 = std::vector<int8_t>
BBBNum2 addp (const BBBNum2& A, const BBBNum2& B) { ... }

Again, the code inside this function can refer to B[j] etc. and use B.size() exactly the same as with the array collection. But now, the size is a run-time property, and can be different for each one.

You would create your result, as in my first post, by giving the size as a constructor argument, and then you can return the vector by-value. Note that the compiler will do this efficiently and not actually have to copy anything if you write:

auto C = addp (A, B);

now for the real work

OK, now that this distraction is at least out of the way, you can worry about actually writing the implementation. I hope you are convinced that using vector instead of a C primitive array does not affect your problem logic or even the (available) syntax of using subscripts. Especially since the problem referred to psudocode, I interpret its use of "array" as "suitable indexable collection" and not specifically the primitive C array type.

The issue of going through 2 sequences together and dealing with differing lengths is actually a general purpose idea. In C++20, the Range library has things that make quick work of this. Older 3rd party libraries exist as well, and you might find it called zip or something like that.

But, let's look at writing it from scratch. You want to read an item at a time from two inputs, but neatly make it look like they're the same length. You don't want to write the same code three times, or elaborate on the cases where A is shorter or where B may be shorter... just abstract out the idea that they are read together, and if one runs out it provides zeros.

This is its own piece of code that can be applied twice, to A and to B.

class backwards_bit_reader {
    const BBBnum2& x;
    size_t index;
public:
    backwards_bit_reader(const BBBnum2& x) : x{x}, index{x.size()}  {}
    bool done() const { return index == 0; }
    int8_t next()
       {
       if (done()) return 0;  // keep reading infinite leading zeros
       --index;
       return x[index];
       }
 };

Now you can write something like:

backwards_bit_reader A_in { A };
backwards_bit_reader B_in { B };
while (!A_in.done() && !B_in.done()) {
   const a = A_in.next();
   const b = B_in.next();
   const c = a+b+carry;
   carry = c/2;  // update
   C[--k]= c%2;
 }
 C[0]= carry;  // the final bit, one longer than the input

It can be written far more compactly, but this is clear.

another approach

The problem is, is writing backwards_bit_reader beyond what you've learned thus far? How else might you apply the same logic to both A and B without duplicating the statements?

You should be learning to recognize what's sometimes called "code smell". Repeating the same block of code multiple times, and repeating the same steps with nothing changed but which variable it's applying to, should be seen as ugly and unacceptable.

You can at least cut back the cases by ensuring that B is always the longer one, if they are of different length. Do this by swapping A and B if that's not the case, as a preliminary step. (Actually implementing that well is another digression)

But the logic is still nearly duplicated, since you have to deal with the possibility of the carry propagating all the way to the end. Just now you have 2 copies instead of 3.

Extending the shorter one, at least in façade, is the only way to write one loop.

how realistic is this problem?

It's simplified to the point of being silly, but if it's not done in base 2 but with larger values, this is actually implementing multi-precision arithmetic, which is a real thing people want to do. That's why I named the type above BBBNum for "Bad Binary Bignum".

Getting down to an actual range of memory and wanting the code to be fast and optimized is also something you want to do sometimes. The BigNum is one example; you often see this with string processing. But we'll want to make an efficient back-end that operates on memory without knowing how it was allocated, and higher-level wrappers that call it.

For example:

void addp (const int8_t* a_begin, const int8_t* a_end,
           const int8_t* b_begin, const int8_t* b_end,
           int8_t* result_begin, int8_t* result_end);

will use the provided range for output, not knowing or caring how it was allocated, and taking input that's any contiguous range without caring what type of container is used to manage it as long as it's contiguous. Note that as you saw with the std::merge example, it's more idiomatic to pass begin and end rather than begin and size.

But then you have helper functions like:

BBBNum2 addp (const BBBNum2& A, const BBBNum2& B)
{
    BBBNum result (1+std::max(A.size(),B.size());
    addp (A.data(), A.data()+A.size(),  B.data(), B.data()+B.size(), C.data(), C.data()+C.size());
}

Now the casual user can call it using vectors and a dynamically-created result, but it's still available to call for arrays, pre-allocated result buffers, etc.

JDługosz
  • 5,592
  • 3
  • 24
  • 45