-3

I am trying to subtract two integers of the same size without using an explicit loop using valarray. For this purpose I've written a function i.e subtract(int *firstarray, int *secondarray). However, the subtraction occurs correctly in function as printed out. But when returned to main() the first two values of array contain garbage. What is my mistake?

int* subtract(int* lastline, int* firstline){// takes two user defined arrays and performs subtraction

    std::valarray<int> foo (firstline, 7);  //  6 6 5 4 5 6 7
    std::valarray<int> bar (lastline,7);    //  1 8 8 8 8 8 8
    std::valarray<int> res (7);

    res=bar-foo; //subtracts two valarrays

    for (size_t i=0; i<NUMBEROFCLASSES;i++){
        cout<<res[i]<<" ";                  //prints 5 -2 -3 -4 -3 -2 -1
   }

    return &res[0];
}


int main(){

int first[7]={6,6,5,4,5,6,7};
int second[7]={1,8,8,8,8,8,8};
int *e= subtract(first, second);
cout<<endl;
for(int i=0; i<7;i++){
    cout<<e[i]<<" ";                       // prints 0 0 -3 -4 -3 -2 -1
    }
return 1;
}
Adil B
  • 14,635
  • 11
  • 60
  • 78
mibrahimy
  • 722
  • 4
  • 18

1 Answers1

2

res is a variable with automatic storage duration, meaning that it will be destroyed right when the function exits. e is a dangling pointer, so accessing it is undefined behavior. You can return a std::valarray instead.

std::valarray<int> subtract(int* lastline, int* firstline){
    // Stuff
    return res;
}
iBug
  • 35,554
  • 7
  • 89
  • 134
  • I was returning the pointer to convert the `valarray` to a basic array. By returning the value, I won't be able to achieve that. – mibrahimy Dec 21 '17 at 15:06
  • 1
    @IbrahimYousaf Return by value then get *another* pointer to it. – iBug Dec 21 '17 at 15:08
  • Great! Thank you. Since the learned fellows have taken down my reputation for amusement, I can't upvote your comment. – mibrahimy Dec 21 '17 at 15:11
  • @IbrahimYousaf But hey, they downvoted you not for amusement. It's because they thought your question was too trivial. Indeed one about returning a pointer to a local variable is trivial (I agree). – iBug Dec 21 '17 at 15:17
  • True, but my initial problem was looking for a method to convert `valarray` to a basic array. – mibrahimy Dec 21 '17 at 15:50
  • @IbrahimYousaf What about dynamic allocation with `new` and `delete`? – iBug Dec 21 '17 at 15:51
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/161744/discussion-between-ibrahim-yousaf-and-ibug). – mibrahimy Dec 21 '17 at 15:52