2

Lauguage : C++

I have to make function 'add' overloaded.

'add' function has array a[] as parameter.

I wrote my code but it doesn't work.

There is no error or caution but it doesn't start.

What is the problem on my code?

int add(int a[], int n, int b[])
{
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += (a[i] + b[i]);
    return sum;
}

int add(int a[], int n=5)
{
    return add(a, n, NULL);
}
3
  • 1
    "It doesn't start" is certainly an incorrect interpretation of events. Commented Nov 7, 2015 at 7:20
  • Does the assignment say that a[] is an array parameter? That is misleading, because it really is a pointer. Arrays aren't pointers and it is good to understand that early on. Commented Nov 7, 2015 at 8:44
  • What do you think passing NULL does? Hint: it's not an array of zeroes. Commented Nov 7, 2015 at 10:55

2 Answers 2

1
sum += (a[i] + b[i]);

indexes b, which can be NULL. That's Undefined Behavior.

A good way to avoid that pitfall is to use std::vector.

Sign up to request clarification or add additional context in comments.

Comments

1

When you declare arguments like array in the way you do (e.g. int a[]) then the compiler actually declares the argument to be a pointer.

And in the three-argument overload of the add function the third argument (b) could be a null pointer which you don't check for. Attempting to dereference a null pointer leads to undefined behavior and a probable crash.

Don't access b if it's a null pointer.


int add(int* a, int n, int* b)
{
    int sum = 0;
    for (int i = 0; i < n; i++)
    {
        if (b == nullptr)
            sum += a[i];
        else
            sum += a[i] + b[i];
    }
    return sum;
}

4 Comments

Um.. you mean that I have to delete NULL in the return add(a, n, NULL). Then, how I can give value NULL or 0 value to b[] if there is no third parameter?
@HoSuk No, I mean you need to add an if (b == nullptr) check in the function.
int add(int a[], int n, int b[]) { if (b == nullptr) for (int i = 0; i < n; i++) b[i] = 0; int sum = 0; for (int i = 0; i < n; i++) sum += (a[i] + b[i]); return sum; }
Ah, b[i] = 0; is an error. Thanks to your modified code, now the program work properly. I really really appreciate your help. Maybe I have to study harder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.