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;
}