用两个 0x00 字节作为前缀 unsigned char 指针数组

Prefix unsigned char pointer array with two 0x00 bytes

例如,如果我有一个 unsigned char *str,其值为 0x68 0x65 0x6C 0x6C 0x6F,我如何在这个数组前加上两个空字节,这样数组就会变成 [0x00 0x00] 0x68 0x65 0x6C 0x6C 0x6F[] = 添加字节)?

我试过 strcat 但这没有产生预期的结果,我想是因为 0x00 字节被视为字符串终止符。

函数strcat用于处理字符串,即以零结尾的字符数组。由于您的数组不是零终止的,因此您不应使用此函数。

相反,如果您想避免手动编码移动,您可以使用 memmovememset 函数。但是,您需要使用 适当(更大)的大小 声明 str 数组(以容纳添加的字节)。 因此,例如:

unsigned char str[7] = { 0x68, 0x65, 0x6C, 0x6C, 0x6F, }; // Note: size must be at least 7
//.. some code
memmove(str+2, str, 5); // Shift along by two bytes (see note, below)
memset(str, 0, 2);      // Add the two 'prefix' zeros

注意 memmove 函数是 safe with overlapping buffers (加粗我的):

Copies the values of num bytes from the location pointed by source to the memory block pointed by destination.
Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.

但是,这仅适用于函数 memmove,不适用于函数 memcpy。使用函数 memcpy,重叠缓冲区是不安全的。

此外,请注意 unsigned char *str 不声明数组(尽管您可以对 string literals 使用类似的语法)。您需要使用已发布代码的(现已更正)版本。