更新时间:2022-05-12 06:03:52
C 中的字符串是字节数组,它们以零结尾。因此,您需要做的就是将数组复制到一个新的缓冲区中,该缓冲区具有足够的空间来容纳结尾的零字节:
Strings in C are byte arrays which are zero-terminated. So all you need to do is copy the array into a new buffer with sufficient space for a trailing zero byte:
#include <string.h>
#include <stdio.h>
typedef unsigned char BYTE;
int main() {
BYTE byteArray[5] = { 0x48, 0x65, 0x6C, 0x6C, 0x6F };
char str[(sizeof byteArray) + 1];
memcpy(str, byteArray, sizeof byteArray);
str[sizeof byteArray] = 0; // Null termination.
printf("%s\n", str);
}