【问题标题】:C - get chars from part of byte arrayC - 从字节数组的一部分获取字符
【发布时间】:2012-11-18 18:36:11
【问题描述】:

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

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

【问题讨论】:

  • 我尝试循环并逐字节复制。我忘了 memcpy。
  • “点”是什么意思?

标签: c pointers char bytearray


【解决方案1】:

要提取数组的一部分,可以使用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 有帮助,但我很少扩展我的问题。请看上面。
【解决方案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]

这将从src复制索引18到251的字节并将它们存储在dest中。

【讨论】:

  • 你对哪一部分有困难?
  • memcpy(dest,&lt;problem-here&gt;index2-index1&lt;/problem-here&gt;, &amp;src[index1]) 部分
  • 我认为您可以在 memcpy 中交换第二个和第三个参数,但这没问题。我又遇到了我在相关编辑中描述的问题,请看一下。
【解决方案3】:

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

范妮是你的阿姨。

【讨论】:

    【解决方案4】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2011-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 2015-02-02
      • 1970-01-01
      • 2016-08-20
      相关资源
      最近更新 更多