Search code examples
c++linuxuart

C++ unsigned char array length


I have in my C++ program unsigned char array of hex values:

unsigned char buff[] = {0x03, 0x35, 0x6B};

And I would like to calculate the size of this array so that I can send it on UART port linux using this function:

if ((count = write(file,buff,length))<0)
{
    perror("FAIL to write on exit\n"); 
}

as I can see the length is int number, and buff is an array which can change size during program execution. can anyone help me how to write it. Thanks


Solution

  • You can do this with an array:

    size_t size = sizeof array;
    

    with your example that give:

    ssize_t count = write(file, buff, sizeof buff);
    if (count < 0 || (size_t)count != sizeof buff) {
      perror("FAIL to write on exit\n");
    }
    

    Note: I use C semantic because write is from lib C.


    In C++, you can use template to be sure that you use sizeof with an array.

    template<typename T, size_t s>
    size_t array_sizeof(T (&array)[s]) {
        return sizeof array;
    }
    

    with your example that give:

    ssize_t count = write(file, buff, array_sizeof(buff));
    if (count < 0 || static_cast<size_t>(count) != array_sizeof(buff)) {
      perror("FAIL to write on exit\n");
    }