Link to home
Start Free TrialLog in
Avatar of nicolac
nicolac

asked on

Accessing structures in functions in C++

I have some functions that take in structures, amongst other things.
eg.
int winapi rectangle(SIZES *pInfo);

...where SIZES is a structure. How can I assign values to the variables of the Structure SIZES? I'v tried creating an object of type SIZES and assigning values using the (.)
 SIZES MySizes;  //create a Sizes object
*mySizesPtr=&mySizes, //pointer       &mySizesRef=mySizes;  //reference

mySizes.version = 0x03000000;

But I'm not sure that this is assigning the values to the right place.
Pls can i have a simple example of how to do this correctly. Pls help!

ASKER CERTIFIED SOLUTION
Avatar of xLs
xLs

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RONSLOW
RONSLOW

Two ways...

int winapi rectangle(SIZES *pInfo) {
  pInfo->xxxx = yyy;
}

or

int winapi rectangle(SIZES *pInfo) {
  SIZES& sizes = *pInfo;
  sizes.xxxx = yyyy;
}

The first accesses directly from the pointer with ->

The second uses a reference, and you can then use '.'

Both of the above will change the thing pointed to by pInfo.

If you take a COPY of the thing pointed to by pInfo and change that, then the original is unchanged.



Both person has replied correctly but RONSLOW's explanation is easy to understand.
what does the -> mean ?
p->x is just shorthand for

(*p).x

ie. it dereferences the pointer to a struct and then gets the member of the struct.

or simpler...

ie. it does a '.' on the object pointed to by p

pointers are a tricky C concept for many to grasp.

even trickier for some is C++ references, which is what I used in the other example.

Avatar of nicolac

ASKER

Thanks, I understand now :)