Search code examples
cpointerscastingpointer-arithmetic

Arithmetic on Casted Pointer


The below code prints a passed string as hex values, I'm using it to check strings which include non-printable characters prior to transmission on a serial network. I understand the code but am just unsure why if we assume that an int on my system is 4 bytes, the pointer doesn't advance by four bytes each time (unsigned int) *s++ is computed by the loop. Could someone please explain why this is the case? Is there some sort of operator precidence like general arithmetic?

static void printhexstring(const char *s) {
while(*s) {
    printf("<%02X> ", (unsigned int) *s++);
}
printf("\n");
}

Solution

  • printf("<%02X> ", (unsigned int) *s++);
    

    You are incrementing the pointer s which is of type char and when this increment is done the pointer s is moved by one byte and not 4 bytes. Casting has no effect on pointer arithmetic here.

    %X converts an unsigned int to unsigned hexa and display the value out so you have the cast unsigned int