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 5776 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 in how many persons are stored..

  // input them 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