Pointers *&

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Yuri

    Pointers *&

    Hello,
    I'm a c++'s newbie. In a BinarySearchTre e data structure I found this
    definition:
    void insert( const Comparable & x, BinaryNode<Comp arable> * & t ) const;
    What does " *& " mean?
    It' s a pointer to a reference? or what?
    Thanks
    Yuri[color=blue]
    >[/color]
  • Jakob Bieling

    #2
    Re: Pointers *&amp;

    "Yuri" <boombastic@lib ero.it> wrote in message
    news:NqUNa.1515 54$lK4.4251900@ twister1.libero .it...[color=blue]
    > Hello,
    > I'm a c++'s newbie. In a BinarySearchTre e data structure I found this
    > definition:
    > void insert( const Comparable & x, BinaryNode<Comp arable> * & t ) const;
    > What does " *& " mean?
    > It' s a pointer to a reference? or what?[/color]


    The other way round. It is a reference to a pointer, meaning that the
    function 'insert' can directlt change the value of the pointer you are
    passing to it.

    hth
    --
    jb

    (replace y with x if you want to reply by e-mail)


    Comment

    • MiniDisc_2k2

      #3
      Re: Pointers *&amp;


      "Yuri" <boombastic@lib ero.it> wrote in message
      news:NqUNa.1515 54$lK4.4251900@ twister1.libero .it...[color=blue]
      > Hello,
      > I'm a c++'s newbie. In a BinarySearchTre e data structure I found this
      > definition:
      > void insert( const Comparable & x, BinaryNode<Comp arable> * & t ) const;
      > What does " *& " mean?
      > It' s a pointer to a reference? or what?
      > Thanks
      > Yuri[color=green]
      > >[/color][/color]

      It's a very important feature that I've used a lot. You probably know what a
      pointer is, it's the address of an object. By using the pointer, the data
      inside the BinaryNode could be modified and passed back. Unfortunately, if
      the function were to modify the address contained in t, that address
      wouldn't be passed back. Thus, the reference (&) is needed. This allows the
      address to be passed back if it is changed. Try this to demonstrate it on
      yourself:

      /* This results in an access violation: data space never allocated */
      void Allocate(int* var)
      {
      var = new int;
      }

      int main()
      {
      int* a;
      Allocate(a);
      *a = 5; // access violation
      return (0);
      }

      This is because the address to the new int is never passed back, so main()
      has no knowledge of that new address. On the other hand:

      /* This works */
      void Allocate(int* &var)
      {
      var = new int;
      }

      int main()
      {
      int* a;
      Allocate(a);
      *a = 5; // works
      return (0);
      }

      This works because of the reference. Because of the reference, main() has
      the knowledge of the new address. Note this does cause a memory leak, but I
      didn't worry about deleting my pointers in this simple example, as this
      example is not to teach you about pointers but rather references.

      --
      MiniDisc_2k2
      To reply, replace nospam.com with cox dot net.


      Comment

      • Stuart Golodetz

        #4
        Re: Pointers *&amp;

        "MiniDisc_2 k2" <MattDelB@nospa m.com> wrote in message
        news:NkVNa.8539 $ZT5.2081@news2 .east.cox.net.. .[color=blue]
        >
        > "Yuri" <boombastic@lib ero.it> wrote in message
        > news:NqUNa.1515 54$lK4.4251900@ twister1.libero .it...[color=green]
        > > Hello,
        > > I'm a c++'s newbie. In a BinarySearchTre e data structure I found this
        > > definition:
        > > void insert( const Comparable & x, BinaryNode<Comp arable> * & t ) const;
        > > What does " *& " mean?
        > > It' s a pointer to a reference? or what?
        > > Thanks
        > > Yuri[color=darkred]
        > > >[/color][/color]
        >
        > It's a very important feature that I've used a lot. You probably know what[/color]
        a[color=blue]
        > pointer is, it's the address of an object. By using the pointer, the data
        > inside the BinaryNode could be modified and passed back. Unfortunately, if
        > the function were to modify the address contained in t, that address
        > wouldn't be passed back. Thus, the reference (&) is needed. This allows[/color]
        the[color=blue]
        > address to be passed back if it is changed. Try this to demonstrate it on
        > yourself:
        >
        > /* This results in an access violation: data space never allocated */[/color]

        Not here it doesn't result in an access violation, and memory for an int is
        quite definitely allocated. The point is that you lose the pointer to the
        memory when the function returns, so you've ended up with a memory leak.
        Furthermore, the pointer passed in will be unchanged after the call, which
        causes the problem you've highlighted below.
        [color=blue]
        > void Allocate(int* var)
        > {
        > var = new int;
        > }
        >
        > int main()
        > {
        > int* a;
        > Allocate(a);
        > *a = 5; // access violation[/color]

        *Now* there is undefined behaviour, which might or might not result in an
        "access violation" (hopefully it will, but anything could happen). The
        reason is that the value of a at this point is indeterminate. In other
        words, you are dereferencing a pointer that points to a random place in
        memory -> undefined behaviour.
        [color=blue]
        > return (0);[/color]

        No brackets necessary around the 0:

        return 0;
        [color=blue]
        > }
        >
        > This is because the address to the new int is never passed back, so main()
        > has no knowledge of that new address. On the other hand:[/color]

        The point in this instance is that you're modifying a local copy of a rather
        than the one you passed to the function.
        [color=blue]
        > /* This works */
        > void Allocate(int* &var)
        > {
        > var = new int;
        > }
        >
        > int main()
        > {
        > int* a;
        > Allocate(a);
        > *a = 5; // works
        > return (0);
        > }
        >
        > This works because of the reference. Because of the reference, main() has
        > the knowledge of the new address.[/color]

        To put it more precisely: Allocate now modifies the pointer you pass in
        rather than a local copy of it, so the pointer a, which is local to main(),
        is modified by the call (assuming, of course, that new succeeds). Thus
        (assuming all went well), a points to a valid int when Allocate returns.

        I know that didn't add a great deal, but I'm not sure I particularly like
        the terminology "main() has the knowledge of the new address" (or even
        "main() knows about the new address", I'm not into quibbling about grammar
        particularly). The thing is that main(), as a C++ function, doesn't "know"
        anything (it's not a living entity, right? :-)). I understand what you mean,
        it's just a bit of a woolly way of putting it... :-) No offence intended,
        incidentally, just trying to make it a little clearer to the OP.

        HTH,

        Stuart.
        [color=blue]
        > Note this does cause a memory leak, but I
        > didn't worry about deleting my pointers in this simple example, as this
        > example is not to teach you about pointers but rather references.
        >
        > --
        > MiniDisc_2k2
        > To reply, replace nospam.com with cox dot net.[/color]


        Comment

        • Alex Leung

          #5
          Re: Pointers *&amp;

          A little mistake, it means that function 'insert' can directly change "the
          pointer" itself.
          "Jakob Bieling" <netsurf@gmy.ne t>
          ???????:be9479$ h9b$04$1@news.t-online.com...[color=blue]
          > "Yuri" <boombastic@lib ero.it> wrote in message
          > news:NqUNa.1515 54$lK4.4251900@ twister1.libero .it...[color=green]
          > > Hello,
          > > I'm a c++'s newbie. In a BinarySearchTre e data structure I found this
          > > definition:
          > > void insert( const Comparable & x, BinaryNode<Comp arable> * & t ) const;
          > > What does " *& " mean?
          > > It' s a pointer to a reference? or what?[/color]
          >
          >
          > The other way round. It is a reference to a pointer, meaning that the
          > function 'insert' can directlt change the value of the pointer you are
          > passing to it.
          >
          > hth
          > --
          > jb
          >
          > (replace y with x if you want to reply by e-mail)
          >
          >[/color]


          Comment

          • Mike Wahler

            #6
            Re: Pointers *&amp;

            Alex Leung <alex@hitogo.co m> wrote in message news:3f085b86$2 @shknews01...[color=blue]
            > A little mistake, it means that function 'insert' can directly change "the
            > pointer" itself.[/color]

            Isn't that what Jakob said?

            "the function 'insert' can directlt change the value
            of the pointer you are passing to it."

            -Mike



            Comment

            • Jerry Coffin

              #7
              Re: Pointers *&amp;

              In article <beaoej$nuv$1@s lb6.atl.mindspr ing.net>, mkwahler@mkwahl er.net
              says...[color=blue]
              >
              > Yuri <boombastic@lib ero.it> wrote in message
              > news:NqUNa.1515 54$lK4.4251900@ twister1.libero .it...[color=green]
              > > Hello,
              > > I'm a c++'s newbie. In a BinarySearchTre e data structure I found this
              > > definition:
              > > void insert( const Comparable & x, BinaryNode<Comp arable> * & t ) const;
              > > What does " *& " mean?
              > > It' s a pointer to a reference? or what?[/color]
              >
              > Other way around. It's a reference to a pointer.[/color]

              ....and, in fact, a pointer to a reference isn't allowed.

              --
              Later,
              Jerry.

              The universe is a figment of its own imagination.

              Comment

              • Chris Ritchey

                #8
                Re: Pointers *&amp;

                "MiniDisc_2 k2" <MattDelB@nospa m.com> wrote in message[color=blue]
                > /* This works */
                > void Allocate(int* &var)
                > {
                > var = new int;
                > }
                >
                > int main()
                > {
                > int* a;
                > Allocate(a);
                > *a = 5; // works
                > return (0);
                > }[/color]

                I had to do this today for the first time, the same program also has
                me working with an array of **, as well for the first time, a very fun
                program :) Anyways I have a question about *&.

                lets say instead of Allocate(int* &var) it's Allocate(char* &var) and
                var = new char[64]. now if a is still int* when I pass it to Allocate
                I would think I would only have to pass it as Allocate((char* )a)...
                however my compiler (sun's optimized compiler) is complaning and it
                wants me to pass it as Allocate((char* &)a) to work. is this normal?

                Comment

                • Stuart Golodetz

                  #9
                  Re: Pointers *&amp;

                  "Chris Ritchey" <rethnor@yahoo. com> wrote in message
                  news:480de79d.0 307071454.67c03 74b@posting.goo gle.com...[color=blue]
                  > "MiniDisc_2 k2" <MattDelB@nospa m.com> wrote in message[color=green]
                  > > /* This works */
                  > > void Allocate(int* &var)
                  > > {
                  > > var = new int;
                  > > }
                  > >
                  > > int main()
                  > > {
                  > > int* a;
                  > > Allocate(a);
                  > > *a = 5; // works
                  > > return (0);
                  > > }[/color]
                  >
                  > I had to do this today for the first time, the same program also has
                  > me working with an array of **, as well for the first time, a very fun
                  > program :) Anyways I have a question about *&.
                  >
                  > lets say instead of Allocate(int* &var) it's Allocate(char* &var) and
                  > var = new char[64]. now if a is still int* when I pass it to Allocate
                  > I would think I would only have to pass it as Allocate((char* )a)...
                  > however my compiler (sun's optimized compiler) is complaning and it
                  > wants me to pass it as Allocate((char* &)a) to work. is this normal?[/color]

                  Yes, it's normal. Perhaps the error message Comeau C++ gives is a little
                  clearer?

                  "ComeauTest .c", line 9: error: initial value of reference to non-const must
                  be an
                  lvalue
                  Allocate((char* )a);

                  I think this is the relevant bit from the Standard, but it really needs
                  someone else to clarify it, because my ability to explain lvalues and
                  rvalues is minimal... :-) As I understand it, an l-value is anything you can
                  take the address of. Beyond that, I'll leave it to someone else, because
                  I'll as like as not get it wrong.

                  "3.10-6
                  An expression which holds a temporary object resulting from a cast to a
                  nonreference type is an rvalue (this includes the explicit creation of an
                  object using functional notation (5.2.3))."

                  What I think is happening is that (char*)a [which is clearly a cast to a
                  non-reference type] creates a temporary char pointer [which is an rvalue]
                  pointing to the same address as does a. Now since you can't bind a temporary
                  to a non-const reference, you can't pass (char*)a as the parameter to the
                  function. If the function took a char pointer by value, or by
                  const-reference, you'd be fine.

                  In any case, casting like this is inherently dodgy, and you really shouldn't
                  be doing it. 'Nuff said.

                  HTH,

                  Stuart.


                  Comment

                  • Chris Ritchey

                    #10
                    Re: Pointers *&amp;

                    > In any case, casting like this is inherently dodgy, and you really shouldn't[color=blue]
                    > be doing it. 'Nuff said.[/color]

                    I agree, but I'm trying to build a char* from a linked link of linked
                    lists...
                    So what I'm doing is building the char*'s first for each of the inside
                    linked linsts, then allocating enough memory from the sum of all the
                    allocated char*. Thought i'd post some code just for kicks:


                    ComNode* current = members;
                    char** objGroups = new char*[numMembers];

                    cout << endl;
                    // The following loop is to generate strings for each ObjectGroup
                    created
                    // by each member, and to calculate the total size of the new
                    data chunk
                    for(int i = 0; i < numMembers, current != NULL; i++, current =
                    current->next)
                    {
                    objGroups[i] = (char*)current->member->StrToken();
                    cout << "|-------------------|" << endl;
                    cout << " MessageSize[" << i << "]: " << *((int*)objGrou ps[i])
                    << endl;
                    cout << " NumberItems[" << i << "]: " <<
                    *(((int*)objGro ups[i]) + 1) << endl;
                    messageSize += *((int*)objGrou ps[i]);
                    }
                    cout << "|-------------------|" << endl << endl;


                    // Begin Building the char*
                    toReturn = (int*)new char[(messageSize += 2 * SOF_INT +
                    SOF_GROUPTYPE + SOF_GROUPID)];
                    // Build the header for this char*
                    *toReturn = messageSize;
                    *(toReturn + 1) = numMembers;
                    data = toReturn + 2;

                    Comment

                    Working...