Link to home
Start Free TrialLog in
Avatar of naseeam
naseeamFlag for United States of America

asked on

How to point pointer to word(2 bytes) after pointer subtraction ?

void 
ModbusPoll::processSpecialParam(ParameterDef pTable[], char * val, unsigned short * ptr_buffIndex)
{
/* some code here */
case Flag_TwoParamReg:
  unsigned short modbus_reg_40045_save_value;
  modbus_reg_40045_save_value =  * ( (unsigned short *) val ) ;
  * ( ( unsigned short * ) val - 1 ) = 0x0003 & modbus_reg_40045_save_value ;

Open in new window


My doubt is if I'm correctly typecasting val to point to 2 bytes, then subtract one from val.
The pointer that is result of subtraction needs to point to 2 bytes so 2 bytes can be
stored.

The code above seems to store two bytes in location pointed to by computed address but how does it know to strore two bytes when I don't explicitly typecast resultant pointer to unsigned short?
Avatar of Ken Butters
Ken Butters
Flag of United States of America image

Hopefully I'm answering what you are asking.

When you increment or decrement a pointer, you are pointing to the previous or next element of the array that the pointer is pointing to.  You are not incrementing or decrementing the address the pointer holds.

Therefore if you subtract 1 from a pointer... it will point to the previous element in the array.  If that element was an unsigned short... that would be 2 bytes (on any machine that I know of anyway).
Avatar of naseeam

ASKER

There is no way of knowing the size of previous element.  Pointer was passed to the function as            char * val

All we know is that pointer points to char.  When we typecast it to unsigned short, then it point to 2 bytes.  When we subtract one from the pointer, how do we know how many bytes the computed pointer points to ?
ASKER CERTIFIED SOLUTION
Avatar of Ken Butters
Ken Butters
Flag of United States of America image

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