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

asked on

Does typecasting what pointer points to affect pointer math?

Assume unsigned short is 1 byte and unsigned int is 2 bytes.  Please consider following code Snippet:

void program(unsigned short *dst, unsigned short const *src, size_t num)
{
      unsigned short status=1;

      /* Now program cell-wise (i.e 8 bytes in one stretch) */
      while ((num > 0) && (status))
      {
            status = m32_program_8byte((unsigned int *)dst, (unsigned int *)src);

            num -= 8;
            dst += 8;
            src += 8;
   }
}

Pointers dst and src were pointing to unsigned short but this is modified so these pointers are pointing to unsigned int.  When pointer math is performed at the end of the function, will dst and src increase by 8 bytes or 16 bytes.

thanks.
SOLUTION
Avatar of ozo
ozo
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
SOLUTION
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
SOLUTION
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
Basically type casting changes the type within the expression in which it has been typecasted - it does not affect the actual type of the declared variable.
m32_program_8byte((unsigned int *)dst, (unsigned int *)src);
no more modifies src and dst than would
m32_program_8byte(dst+8,src+8);
ASKER CERTIFIED SOLUTION
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
>> Just to augment what sunnycoder
oops, and ozo -- sorry ozo for missing you out :)
Avatar of naseeam

ASKER

Excellent responses.  Problem solved.  Clear and detailed explanations.