如何从字节数组的一部分获取字符数组或字符指针?假设我在字节数组中有一个可变大小的字符串,它从数组的第18个字节开始,到数组末尾的第4个字节结束。我该如何获取它?
编辑: 那么点(dot)怎么办?我应该在字节数组中有点,但是当我用memcpy复制时,我的字符串没有点。我该怎么解决这个问题?
你可以使用memcpy来复制任意字节范围:
const int index1 = 18; // start index in src
const int index2 = 252; // end + 1 index in src
char src[256]; // source array
char dest[256]; // destination array
memcpy(dest, &src[index1], index2 - index1);
// copy bytes from src[index1] .. src[index2 - 1]
// inclusive to dest[0] .. dest[index2 - index1 - 1]
这将从索引18到251复制来自src
的字节,并将其存储在dest
中。
memcpy(dest, index2-index1 的问题在这里, &src[index1])
部分 - Aniket Inge要从数组中提取部分内容,可以使用memcpy
函数。
#include <string.h>
char dst[4];
/* Here, we can assume `src+18` and `dst` don't overlap. */
memcpy(dst, src + 18, 4);
C11 (n1570), § 7.24.2.1
memcpy
函数
memcpy
函数将从s2
指向的对象中复制n个字符到s1
指向的对象中。如果在重叠的对象之间进行复制,则行为未定义。
谷歌一下memcpy
的用法,它会满足你的问题。
const char *buffer = "I AM A VERY VERY VERY VERY VERY VERY VERY VERY BIG STRING";
char buffer2[4];
memcpy(buffer2, (buffer+18), 4);
就这么轻松愉快。
memcpy(destination, source, count);
source+n
可以跳过n
个字节(不应超出源数组))一个小警告:如果目标与源相同,则必须将所有操作数保存在索引中。