Nested Structs and Pointers Confusion

Ok, basically i don't understand why its not outputting 1979. I thought that with the pointers it would be several -> and it would work fine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>
using namespace std;

int main(){


struct movies_t {
  string title;
  int year;
};

struct friends_t {
  string name;
  string email;
  movies_t * favorite_movie;
  } 

friends_t * pfriends = new friends_t;
//friends_t * pfriends = &maria;

pfriends->favorite_movie->year=1979;

cout<<pfriends->favorite_movie->year<<endl;

	system("PAUSE");
return 0;
}
Last edited on
You forgot to use 'new' on favorite_movie. :P

Also, don't forget to 'delete' your pointers (in order!!) when you're done with them because you're using 'new'. Otherwise, you'll notice a considerable slowdown given enough time because you aren't freeing your memory. ^_^

Here is some fixed code:
1
2
3
4
5
6
7
8
9
10
11
12
13
friends_t * pfriends = new friends_t;
//friends_t * pfriends = &maria;

pfriends->favorite_movie = new movies_t;
pfriends->favorite_movie->year = 1979;

cout << pfriends->favorite_movie->year << endl;

//delete the pointers in the reverse order that you used 'new' on them
delete pfriends->favorite_movie;
pfriends->favorite_movie = 0; //a simple formality
delete pfriends;
pfriends = 0; //again, formality 


rpgfan
Last edited on
Topic archived. No new replies allowed.