Vector Problem By Pointers
Nov 11, 2011 at 6:51pm UTC
hi every one.
i have a struct which contains a vector<int>. when i define a pointer of that struct and try to add elements into that vector. i get this exception:
Unhandled exception at 0x624d31ea (msvcr90d.dll) in Test.exe: 0xC0000005: Access violation reading location 0xcdcdcdc1.
does anyone has any idea about this problem?
i know if i don't use pointers, it'll work fine, but i want to solve that by having pointers.
Nov 11, 2011 at 6:53pm UTC
solved! i should've used "new" instead of "malloc" :D
Nov 11, 2011 at 7:05pm UTC
please, show your code .:)
Nov 11, 2011 at 7:12pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include<iostream>
#include<vector>
using namespace std;
struct MyStruct
{
vector<int > arr;
};
int main()
{
MyStruct *s = new MyStruct;
//s = (MyStruct *)malloc(sizeof(MyStruct));
s->arr.push_back(2); //Exception happens here...
return 0;
}
Nov 11, 2011 at 7:21pm UTC
there aren't any error .
I use VS2010 to compile your code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include<iostream>
#include<vector>
using namespace std;
struct MyStruct
{
vector<int > arr;
};
int main()
{
MyStruct *s = new MyStruct;
//s = (MyStruct *)malloc(sizeof(MyStruct));
s->arr.push_back(2); //Exception happens here...
cout<<s->arr.at(0);
return 0;
}
Last edited on Nov 11, 2011 at 7:22pm UTC
Nov 11, 2011 at 7:27pm UTC
of course there's no errors now! i told i solved it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<iostream>
#include<vector>
using namespace std;
struct MyStruct
{
vector<int > arr;
};
int main()
{
MyStruct *s;
s = (MyStruct *)malloc(sizeof (MyStruct));
s->arr.push_back(2); //Exception happens here now...
return 0;
}
i forgot to clear the comment in the latest post :)
Nov 11, 2011 at 7:29pm UTC
Have a nice day :)
Nov 11, 2011 at 11:53pm UTC
i should've used "new" instead of "malloc"
*sigh* neither.
1 2
MyStruct s;
s.arr.push_back(2);
Topic archived. No new replies allowed.