Reputation: 363
#include <iostream>
#include <string.h>
#include <deque>
using namespace std;
void insertValues(deque<float*> mydeque)
{
*mydeque.at(0)=12;
}
void initArray(deque<float*> mydeque, float* values)
{
for(int i=0;i<3;i++)
mydeque.push_back(values+i);
}
int main ()
{
float values[3];
deque<float*> mydeque;
initArray(mydeque,values);
insertValues(mydeque); //Gives out of range - memory error
cout<<values<<" "<<values+1<<" " <<values[0]<<endl;
values[0]=5;
cout<<values<<" "<<values+1<<" " <<values[0]<<endl;
getchar();
return 0;
}
In the above code, i bump into memory issues on calling insertValues() function and it gives out of range error but i don't know why that happens because the deque has the correct addresses which i verified.
Where am i going wrong?
Upvotes: 0
Views: 68
Reputation: 21576
Your problem is here.
void initArray(deque<float*> mydeque, float* values)
{
for(int i=0;i<3;i++)
mydeque.push_back(values+i);
}
mydeque
is going to be a copy of whatever you passed, mydeque
was filled and later destroyed. The originally passed parameter remains untouched.
Modify it to take the parameter by reference...
void initArray(deque<float*>& mydeque, float* values)
{
for(int i=0;i<3;i++)
mydeque.push_back(new float(values+i);
}
Though your code will work as it is, but you should not use a std::deque
of pointers to float
. Its way too fragile and its less performant in time and memory. Prefer to use integral types by value.
Upvotes: 3