2

如何从部分字节数组中获取 char 数组或 char 指针?假设我在字节数组中有可变大小的字符串,它从 18 个字节开始,到数组末尾的 4 个字节结束。我怎样才能得到这个?

编辑:点呢?我应该在那个字节数组中有点,但是当我通过 memcpy 复制时,我得到没有点的字符串。我怎样才能解决这个问题?

4

4 回答 4

2

好吧,您可以使用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.

于 2012-11-18T18:40:07.987 回答
2

要提取数组的一部分,您可以使用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.1memcpy函数
memcpy函数将 n 个字符从 指向的对象复制到 指向s2的对象中s1。如果复制发生在重叠的对象之间,则行为未定义。

于 2012-11-18T18:40:15.013 回答
1

谷歌使用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);

芬妮是你的阿姨。

于 2012-11-18T18:39:43.013 回答
0

memcpy(目的地,来源,计数);

  • 目的地 = 存储区 ( !important destination_SIZE >= count)
  • 源 = 保存要复制的数据的数组(默认起始索引 = 0,但source+n可以跳过n字节(您不应该超出源数组))
  • count = 将复制多少字节。

一个小警告:如果目标与源相同,则必须将所有操作数保存在索引中。

于 2018-05-15T11:51:59.260 回答