'How to delete bytes from a byte array in between in C?

Given a byte array buff of length n:

unsigned char buff[n] = "....." // len n

I want to delete m characters at position pos,

0 < pos, m, pos + m < n

I tried using memmove:

memmove(buff + pos, buff + pos + m, n - (pos + m) + 1);

But this doesn't work for byte array as we don't have '\0' terminator for this buff (but we know its length)

How do I delete bytes in between? Anyone please help

Edit: Sample input,

Pos    Data
0000  03 00 02 ef 02 f0 80 64 00 08 03 eb 70 82 e0 40
0010  00 ff 30 00 00 00 00 b3 47 43 00 00 00 00 00 00
0020  00 1e 00 c4 00 00 00 00 00 00 00 44 00 65 00 66
0030  00 61 00 75 00 6c 00 74 00 41 00 6c 00 74 00 53

Say I want to delete the highlighted bytes from packet.

New paket,

Pos    Data
0000  03 00 02 ef 02 f0 80 64 00 08 03 00 00 00 00 00
0010  00 00 44 00 65 00 66 00 61 00 75 00 6c 00 74 00
0020  41 00 6c 00 74 00 53



Solution 1:[1]

This would erase m chars in an array without terminating null character.

int main() 
{
    int pos = 1, m = 3;
    
    unsigned char arr[8] = {1,2,3,4,5,6,7,8};

    memmove(arr + pos, arr + pos + m, sizeof(arr)/sizeof(arr[0]) - pos - m);

  // if required to zero-out the remaining elements
   memset(arr + sizeof(arr)/sizeof(arr[0]) - m, 0, m);

    for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++)
        printf("%hhu ", arr[i]);
    return 0;
}

Output: 1 5 6 7 8 0 0 0

Solution 2:[2]

You probably want something like this:

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

void Display(const char buff[], int nb)
{
  for (int i = 0; i < nb; i++)
    printf("%d ", buff[i]);

  printf("\n");
}

int main()
{
  unsigned char buff[20] = { 0,1,2,3,4,5 };
                      // buff has room for 20 elements
  int nbelements = 6; // but there are only 6 meaningful elements

  Display(buff, nbelements);

  int pos = 1;         // delete from element 1
  int nbtodelete = 2;  // delete 2 elements
  memmove(buff + pos, buff + pos + nbtodelete, nbelements - pos - 1);
  nbelements -= nbtodelete;

  Display(buff, nbelements);
}

Output:

0 1 2 3 4 5
0 3 4 5

It's pretty self explanatory.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jabberwocky