-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;
}
7
  • 4
    The local objects will be destroyed when get ouf of the function; the returned pointer becomes dangled. Commented Dec 21, 2017 at 14:59
  • 4
    res is a local variable it is gone after the call to subtract(). You can't return a pointer to a local. Commented Dec 21, 2017 at 14:59
  • Please read a couple of good beginner books. Learn about scoping and life-time. Commented Dec 21, 2017 at 15:00
  • Should I declare it static? Or is there any other better method? Commented Dec 21, 2017 at 15:00
  • 3
    Return res by value. Commented Dec 21, 2017 at 15:01

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

7 Comments

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.
@IbrahimYousaf Return by value then get another pointer to it.
Great! Thank you. Since the learned fellows have taken down my reputation for amusement, I can't upvote your comment.
@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).
True, but my initial problem was looking for a method to convert valarray to a basic array.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.