Hello everybody!
Recently while i was experimenting with some code written in c++ i noticed something that confused me a bit. In that code i had to deal with 2 structs :

struct date
    string day;
    int month; 
    int dday;
   int year; };

and the other struct

struct note
     date d;
     string notice;  };

I noticed that when i was passing in a function i built, an instance of note struct as a pointer parameter my program kept crashing continuously, although compiler wasn't complaining. To make myself clear :

void myFunction(note* n, ...other parameters...)
    cout << n->d.day << endl;
   cout << n->d.month << endl;

I'm sure that my program crashed because of that piece of code


i'm sure because i tested it in debug mode.
When i wrote my function differently i had no problem running my program :

void myFunction(note& n, ..other parameters...)
    cout << n.d.day << endl;
    cout << n.d.month << endl;

Has anyone got an idea why the pointer parameter and the arrow
caused that problem? Looking forward to reading your ideas and thoughts...Thank you in advance for your time...


7 Years
Discussion Span
Last Post by iJimJones

Thank you very much tux4life, it didn't even cross my naive mind...



Thanks God, -> and . have the same precedence and associativity.
The OP example with a pointer parameter works fine in VC++ 2008.
Diagnosis: insufficient info ;)


As already pointed out, the . and -> have the same precidence. Also, they are L-to-R associative, so you did not need the parenthesis (other than to make it simpler to understand).

It looks to me like your function header is using old-fashioned C method for passing something "by reference", but I am guessing that the function call is not doing its part.

function myFunc (struct note *x) // C style - x is ptr to a struct note

struct note n;
myFunc(&n); // C style - pass a copy of ptr to n

C++ provides a way to avoid the reference/dereference dance on the function call/function definition that we had to do in C to simulate "call-by-reference". It did so by introducing the prefix operator, &, for parameters in the parameter list of the function definition to mean call-by-reference. This has a different meaning than other contexts for a unary-& (such as the one above in the function call argument). C++ was able to introduce this new way to use the & because the unary-& was invalid (in C) in a parameter list so there was no ambiguity in adding this.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.