如何从 C 中的字节数组中删除字节?

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

给定一个长度为 n 的字节数组 buff:

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

我想删除 pos

位置的 m 个字符

0 < pos, m, pos + m < n

我尝试使用 memmove:

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

但这不适用于字节数组,因为我们没有这个 buff 的“\0”终止符(但我们知道它的长度)

如何删除中间的字节?任何人请帮助

编辑:示例输入,

位置 数据
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

假设我想从数据包中删除突出显示的字节。

新包,

位置 数据
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

这将擦除数组中的 m 个字符而不终止空字符。

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;
}

输出:1 5 6 7 8 0 0 0

您可能想要这样的东西:

#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);
}

输出:

0 1 2 3 4 5
0 3 4 5

不言自明。