【问题标题】:Copying an array of int8_t in C在 C 中复制 int8_t 数组
【发布时间】:2017-06-19 17:43:21
【问题描述】:

我有以下几点:

int8_t rtp[size];
int8_t holding[size];

我想将rtp 中的值复制到holding

【问题讨论】:

  • 我们不是编码服务。你有什么问题?你试过什么?为什么它不起作用?

标签: c arrays copy


【解决方案1】:

使用memcpy() 进行简单复制。

无论对象的类型如何,这都有效。
如果目标是复制整个对象,确保大小相同是一个很好的保障。

assert(sizeof holding == sizeof rtp);
memcpy(holding, rtp, sizeof holding);

如果对象可能重叠 - 或不确定,请使用 memmove()
这有时会有点慢。通常这种潜在的轻微性能降低是微不足道的。

memmove(holding, rtp, sizeof holding);

【讨论】:

  • 通过在两者上使用sizeof,您确实可以将它们都放在自动存储中,因此它们不能重叠。
  • @ikegami 是的。重叠需要一些复杂的东西,比如union { some_type a; some_other_type b; } u; memmove(&u.a, &u.b, sizeof u.a);
【解决方案2】:

您可以使用memcpy 复制整个数组。

memcpy(holding, rtp, size * sizeof(int8_t));

【讨论】:

    【解决方案3】:

    我认为你可以这样做

    int i;
    for(i = 0; i < size/*The size of the array*/, i++){
     holding[i] = rtp[i];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 2023-03-10
      • 2013-12-20
      • 1970-01-01
      相关资源
      最近更新 更多