2

I am trying to loop over an uint8_t array inside a function. I am passing the pointer to the array and the number of elements in the array. If I now try to print the number, this gives me some weird result, if I compare it to looping over an int array.

#include <iostream>

void loop_uint8_t(uint8_t *array, uint8_t array_size)
{
    for (uint8_t *p = array; p != array + array_size; ++p)
    {
        std::cout << "number (cast int)  " << (int)*p << std::endl;
        std::cout << "number (no cast)   " << *p << std::endl;
        printf("number (printf)    %d\n", *p);
    }
}

void loop_int(int *array, int array_size)
{
    for (int *p = array; p != array + array_size; ++p)
    {
        std::cout << "number (no cast)   " << *p << std::endl;
        printf("number (printf)    %d\n", *p);
    }
}

int main()
{
    // loop over uint8_t array
    std::cout << "Loop over uint8_t array:" << std::endl;
    uint8_t a[3] = {10, 20, 30};
    loop_uint8_t(a, 3);

    // loop over int array
    std::cout << "Loop over int array:" << std::endl;
    int b[3] = {10, 20, 30};
    loop_int(b, 3);

    return 0;
}

The output:

Loop over uint8_t array:
number (cast int)  10
number (no cast)

number (printf)    10
number (cast int)  20
number (no cast)   
number (printf)    20
number (cast int)  30
number (no cast)
number (printf)    30
Loop over int array:
number (no cast)   10
number (printf)    10
number (no cast)   20
number (printf)    20
number (no cast)   30
number (printf)    30

So I have to cast the uint8_t to int in order to print it like I am used to with int's (i.e. using *p). If I don't cast, some weird character (new line plus whitespace?) is printed. Why is this?

Will I also run into trouble when using *p to index another array (without casting)?

rinkert
  • 6,593
  • 2
  • 12
  • 31
  • 4
    `uint8_t` is likely a typedef for `unsigned char`. `std::cout<<*p` prints a character whose ASCII code is `(int)*p`, not the numerical value. When you write `std::cout << 'A'`, you probably expect to see `A` and not `65` – Igor Tandetnik May 02 '20 at 22:45
  • ascii decimal 10 = \n – pm100 May 02 '20 at 22:47
  • @IgorTandetnik Ah I see, that makes sense thx. So no problems with indexing. – rinkert May 02 '20 at 22:49

0 Answers0