Search code examples
cmemcpyunsigned-char

C memcpy unsigned char to 1 element unsigned char array for checksum calculation


There is a char array ACKbuffer[2] so I first cast to unsigned char the element that I want but it's giving me an error when I try to memcpy it to an unsigned char array.

//first element is checksum
unsigned char ack_csum;
ack_csum = (unsigned char)ACKbuffer[0];
//second element is ACK which needs to be run through checksum 
//in a checksum function that accepts unsigned char array as parameter
unsigned char ACK_actual = (unsigned char)ACKbuffer[1];
unsigned char ACK [1];
memcpy(ACK, ACK_actual, 1);

Error:

note: expected ‘const void * restrict’ but argument is of type ‘unsigned char’
 extern void *memcpy (void *__restrict __dest, const void *__restrict __src,
              ^~~~~~
swap_client.c: In function ‘swap_write’:
swap_client.c:185:17: warning: passing argument 2 of ‘memcpy’ makes pointer from integer without a cast [-Wint-conversion]
     memcpy(ACK, ACK_actual, 1);

I also tried another way but I get invalid initializer:

unsigned char ACK_actual = (unsigned char)ACKbuffer[1];
unsigned char ACK [1] = ACK_actual;

Ideally, I want my ACK array to hold that value from ACKbuffer.


Solution

  • In this call of memcpy

    memcpy(ACK, ACK_actual, 1);
    

    the variable ACK_actual has the type unsigned char

    unsigned char ACK_actual = (unsigned char)ACKbuffer[1];
    

    but the function expects a pointer type.

    Just write

    memcpy(ACK, ACKbuffer + 1, 1);
    

    As for the second code snippet then you should write

    unsigned char ACK_actual = (unsigned char)ACKbuffer[1];
    unsigned char ACK [1] = { ACK_actual };