Yaroslav Kirillov Yaroslav Kirillov - 1 month ago 9
C Question

String assignment to uint8_t in c

I am trying to assign string to

uint8_t
buffer in IAR, but I get a warning message.

rx_buffer.rx_struct.RESP.RESPOND
is
struct field
of
uint8_t
type.

My code is:

strncpy(rx_buffer.rx_struct.RESP.RESPOND, (uint8_t *)'NS,', 3);


And the associated warning message is the following:

Warning[Pe1422]: multicharacter character literal (potential portability problem)
Warning[Pe167]: argument of type "uint8_t *" is incompatible with parameter of type "char *",
Warning[Pe167]: argument of type "uint8_t *" is incompatible with parameter of type "char const"


I have written a workaround :

rx_buffer.rx_struct.RESP.RESPOND[0] = 'N';
rx_buffer.rx_struct.RESP.RESPOND[1] = 'S';
rx_buffer.rx_struct.RESP.RESPOND[2] = ',';


But I'm not satisfied with it. What is the correct way to do that?

Answer

You are using single quotes but you need double quotes ("NS,") , and take a look to Stop using strncpy already!, in this case it should work as expected because you don't want the trailing '\0', but don't use it.

Use memcpy or memmove, also (as a question of style) don't use magic numbers like 3:

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

#define MAX_SIZE 3

int main(void)
{
    uint8_t arr[MAX_SIZE];

    memmove(arr, "NS,", MAX_SIZE);
    for (int i = 0; i < MAX_SIZE; i++) {
        printf("%c", arr[i]);
    }
    printf("\n");
    return 0;
}
Comments