cpointersmathuint8tuint16

Do I need to use `uint8_t` to do arithmetics on a `uint8_t` pointer?


I have an array of unsigned 8 bit integer, however the length of this array can be higher than 255. I want to use pointer arithmetics instead of array indexing. Can someone explain me if the following code is acceptable or not? My doubt is that the ind variable has a different type with respect to buff and this might be seen as bad programming.

#include <stdio.h>
#include <stdint.h>

int main(){
    uint8_t buff[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int16_t ind;
    
    ind = 1;
    
    printf("%u\n", *(buff + 1));
    printf("%u\n", *(buff + ind));
}

Godbolt shows a small difference between *(buff + 1) and *(buff + ind) but it seems to work.


Solution

  • Most types are converted to int before doing arithmetics (especially for pointer arithmetics), so whether you use uint8, uint16 or uint32 for ind has little consequence.

    what you are doing is adding something to the pointer, which is an address (on 32 or 64 bits), meaning the type pointed by it (uint8_t in your case) has absolutely no effect on the type of the pointer.

    However, do remember that the size of the object pointed matters a lot in pointer arithmetics, since it will not move byte per byte but object by object.

    uint8_t *char_ptr = 0x1000;
    uint32_t *int_ptr = 0x1000;
    
    char_ptr += 1;
    int_ptr += 1;
    
    printf("0x%x", char_ptr); // 0x1001
    printf("0x%x", int_ptr);  // 0x1004