Re: arrow operator

From: Sheldon Simms (sheldonsimms_at_yahoo.com)
Date: 10/29/03


Date: Wed, 29 Oct 2003 10:53:16 -0500

On Wed, 29 Oct 2003 07:24:28 -0800, Jason wrote:

> Hi everyone:
>

> For Example:
>
> struct reptile *animalPtr

It would be easier to help you if you showed at least some
sample declaration for struct reptile. Since you haven't I'll
provide one:

struct reptile
{
   unsigned int snakes;
   unsigned int aligator;
};

>From here on out, I'll assume that this is your structure.

> I was trying to pass a pointer to a structure to a function, where the
> pointer is pointing to one of the members in the structure, is this
> possible???
> Within foo, I was hoping to be able to change the value of the object
> in the structure.

The idea isn't bad, but you are confusing yourself about what
pointer is pointing where. Let's look at expressions:

  animalPtr

this is a pointer to struct reptile

  animalPtr->snakes

this is *not* a pointer. this the "snakes" member of struct reptile,
which is an unsigned int. The "arrow" operator works equivalently
to the following expression

  (*animalPtr).snakes

let's break this up into parts:

  *animalPtr

this is a struct reptile.

  (*animalPtr)

this is still a struct reptile, the parentheses are
necessary when combining * and . to do the same work as ->

  (*animalPtr).snakes

is the "snakes" member of struct reptile -- an unsigned int

Now to get to what you want to do:

> foo(animalPtr->snakes);
> foo(animalPtr->aligator);

Do you see now that you are not passing pointers to the
members of struct reptile; you are passing the members
themselves. This is easy to correct:

  foo(&animalPtr->snakes);
      ^
  foo(&animalPtr->aligator)
      ^

> For Example:
>
> foo(???){ /* not sure what the parameters will be */

Just use a parameter of the type you want to pass. In this case
that's

  unsigned int *

  void foo (unsigned int * xyz);

Notice that this function doesn't really have anything to do
with struct reptile, because the members of struct reptile are
just plain old unsigned ints like any others.

> if(blah < blah2)
> ??? = 100 /* where ??? is the input to this function */

       *xyz = 100;

As you would expeect.

Just to be complete, I will point out that you can also pass pointers
to a structure, if you wish. But then the function has access to the
entire structure, not just one member:

  void bar (struct reptile * animalPtr)
  {
    animalPtr->snake = 50;
    animalPtr->aligator = 150;
  }

-Sheldon

p.s. It's spelled "alligator"