Home > Software design >  Is there a function for moving the contents of a char array a certain amount of addresses back in C
Is there a function for moving the contents of a char array a certain amount of addresses back in C

Time:10-05

I have the following code for Arduino (C ). This is for a checksum consisting of 2 characters forming a base 16 value between 0 and 255. It takes int outputCheckSum and converts it to char outputCheckSumHex[3].

itoa (outputCheckSum, outputCheckSumHex, 16)
  if (outputCheckSum < 16) { //Adds a 0 if CS has fewer than 2 numbers
    outputCheckSumHex[1] = outputCheckSumHex[0];  
    outputCheckSumHex[0] = '0';
  }

Since the output of itoa would be "X" instead of "0X" in the event of X having fewer than 2 characters, the last 3 lines are to move the characters one step back.

I now have plans to scale this up to a CS of 8 characters, and I was wondering whether there exists a function in C that can achieve that before I start writing more code. Please let me know if more information is required.

CodePudding user response:

You should be able to use memmove, it's one of the legacy C functions rather than C but it's available in the latter (in cstring header) and handles overlapping memory correctly, unlike memcpy.

So, for example, you could use:

char buff[5] = {'a', 'b', 'c', '.', '.'};
memmove(&(buff[2]), &(buff[0], 3);
// Now it's {'a', 'b', 'a', 'b', 'c'} and you can replace the first two characters.

Alternatively, you could use std::copy from the algorithm header but, for something this basic, memmove should be fine.

CodePudding user response:

You can use memmove in <cstring> for this. It does not check for terminating null characters, but instead copies num bytes (third argument) and works with overlapping regions as well.

void* memmove(void* destination, const void* source, size_t num);
  • Related