Vector Problem By Pointers

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.
solved! i should've used "new" instead of "malloc" :D
please, show your code .:)
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;
}
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;
}

2
Last edited on
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 :)
Have a nice day :)
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.