0

Trying to make a program that sums 5 digit numbers by each digit. For some reason when I attempt to print individual elements of an array (one element at a time running 5 times) I get the correct value of 69134. But when I print them together:

int *addArray(int arr1[], int arr2[]){

    int arrSum[5];
    int r=0;
    for(int i=4; i>=0; i--){
        arrSum[i]=(arr1[i]+arr2[i]+r)%10;
        r=((arr1[i]+arr2[i]+r)>=10);
    }
    return arrSum;
}

int main(){

    using namespace std;
    int data1[5]={1,2,3,4,5};
    int data2[5]={5,6,7,8,9};
    int *arrSum=addArray(data1,data2);
    cout << arrSum[0] << arrSum[1] << arrSum[2] << arrSum[3] << arrSum[4];
    return 0;

}

I end up with the result 60000. Anyone know what is going on?

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
Anonimus
  • 13
  • 3

1 Answers1

2

In addArray you are returning a pointer to a local variable (arrSum), which results in undefined behaviour. You should either pass in the result array from the calling function, or allocate the array dynamically. For example, using the first approach:

void addArray(const int arr1[], const int arr2[], int arrSum[])
{
    int r=0;
    for(int i=4; i>=0; i--)
    {
        arrSum[i]=(arr1[i]+arr2[i]+r)%10;
        r=((arr1[i]+arr2[i]+r)>=10);
    }
}

int main()
{
    int data1[5]={1,2,3,4,5};
    int data2[5]={5,6,7,8,9};
    int arrSum[5];

    addArray(data1,data2,arrSum);
    cout << arrSum[0] << arrSum[1] << arrSum[2] << arrSum[3] << arrSum[4];
    return 0;
}
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • 1
    Remove `int arrSum[5];` – drescherjm Jan 14 '15 at 23:19
  • Hi, why am I not allowed to pass a pointer (i.e. allowed to use `arrSum` from main as a pointer to the first element of the array `arrSum` in `addArray`)? – Anonimus Jan 16 '15 at 01:32
  • You can return a pointer, but the pointer has to point to valid data. Your local array goes out of scope when the function returns, so your pointer in this case points to invalid data. – Paul R Jan 16 '15 at 01:34
  • I see. But why do the changes to `arrSum` in the function `addArray` affect the value of `arrSum` in `main`? Doesn't the function `addArray` create a local version of `arrSum` that overrides the `main` version? – Anonimus Jan 21 '15 at 17:56
  • @Anonimus: in C and related languages arrays are never passed by value - a pointer to the first element is passed, which is effectively pass-by-reference semantics. – Paul R Jan 21 '15 at 18:24