Jump to content
  • Advertisement


This topic is now archived and is closed to further replies.


How do I know when to use what? Reference/pointers/etc..

This topic is 5993 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I understand the usage of pointers of pointers and referenced variables..but I''m so confused as to when to use them in certain situations. For example, the following code will not work/gives me errors..
// (vector/string included, using namespace all setup, etc)

struct person_t {
   string name;
   string address;
//i know this will only read a single word and not the full 

//line but thats beside the point for now.

void addperson(vector <person_t> *tmp, int *num) {
  cout << "Enter name: ";
  cin >> tmp[num-1].name;
  cout << "Enter address: ";
  cin >> tmp[num-1].address

void main() {
  vector <person_t> database;
  // input file..read in how many persons are stored..

  // input them in..works fine..

  while (true) {
     addperson(tmp, numOfPeople);
So why doesnt that work? I get errors in the "addperson" function, or get invalid page faults. Should I be using references? If so, do I only put a & before the variables in the function declaration, in the function itself, or in the arguments from which the function is being called somewhere else in the program? Or should pointers be used? If so, why doesn''t the code above work?

Share this post

Link to post
Share on other sites
You''re num is a pointer, not an actual integer. When you say num++, you''re not incrementing the actual number stored there. You need to dereference the pointer: *num++. In this situation, though, there''s no real point in passing num as a pointer. It''ll save you a lot of hassle.

P.S. You need to reference num as *num anywhere in the code (i.e. the array indexes) to use the actual value. Otherwise, you''re using the pointer value, which is most likely causing your function to access memory outside of your array boundaries.

Share this post

Link to post
Share on other sites
Ok, but I get errors in regards to using the vector of person_t as well, errors like "left of resize not a struct, etc, etc"

Share this post

Link to post
Share on other sites
You can''t use the ''.'' operator on a pointer to a class or struct. You need to use the -> operator. So, for example, you can resize tmp by doing tmp->resize(*num)

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!