Search code examples
ciotazure-sphere

When char array is passed to a method, the array looses its value


I have method which accepts "constant char*" as a parameter. But when I pass the below array to the method "*SendUartMessage(int uartFd, const char dataToSend)**" only first two hexadecimal values are showing inside the method in the parameter. To be precise as the third value is zero 0x00, it blocks the other values pass inside the method. Can any one provide solution to pass all the array value inside the method.

const char updateAllChannelData[] = { 0x01, 0x06, 0x00, 0x19, 0x00, 0x01, 0x99, 0xCD };
            SendUartMessage(uartFd, updateAllChannelData);

This is the method

static void SendUartMessage(int uartFd, const char* dataToSend)
{
    size_t totalBytesSent = 0;
    size_t totalBytesToSend = strlen(dataToSend);
    int sendIterations = 0;
    close(r1PinFd);
    r1PinFd = GPIO_OpenAsOutput(MIKROE_PWM, GPIO_OutputMode_PushPull, GPIO_Value_High);
    while (totalBytesSent < totalBytesToSend) {
        sendIterations++;

        // Send as much of the remaining data as possible
        size_t bytesLeftToSend = totalBytesToSend - totalBytesSent;
        const char* remainingMessageToSend = dataToSend + totalBytesSent;
        ssize_t bytesSent = write(uartFd, remainingMessageToSend, bytesLeftToSend);
        if (bytesSent == -1) {
            Log_Debug("ERROR: Could not write to UART: %s (%d).\n", strerror(errno), errno);
            exitCode = ExitCode_SendMessage_Write;
            return;
        }

        totalBytesSent += (size_t)bytesSent;
    }
    int c, d;

    sleep(5);
    close(r1PinFd);
    r1PinFd = GPIO_OpenAsOutput(MIKROE_PWM, GPIO_OutputMode_PushPull, GPIO_Value_Low);

    Log_Debug("Sent %zu bytes over UART in %d calls.\n", totalBytesSent, sendIterations);
}

Solution

  • The array has a 0 byte at index 2. strlen calculates the length of a C-string, that is, a null terminated (0 byte terminated) array. Treating your array as a string, the length is 2. If you want to know the real length of the array you have to pass it as a parameter:

    const char updateAllChannelData[] = { 0x01, 0x06, 0x00, 0x19, 0x00, 0x01, 0x99, 0xCD };
    SendUartMessage(uartFd, updateAllChannelData, sizeof(updateAllChannelData));
    
    static void SendUartMessage(int uartFd, const char* dataToSend, size_t totalBytesToSend)
    {
       ...
    }