【问题标题】:Copy a structure to a member of another structure将结构复制到另一个结构的成员
【发布时间】:2014-05-28 09:28:42
【问题描述】:

我在 SDCC 3.4 上,这是一个乐器的 MIDI 项目,我为此苦苦挣扎了几天……我什至觉得有点难以解释,所以在这里我尝试做一个更好的例子。基本上,我正在扫描按钮按下、发送 MIDI 信息并相应地点亮 LED。我需要的是一种数据库,其中包含与每个按钮相关的所有数据,其中一部分必须是恒定的(按钮和 LED 的 ID),而一部分可以是可变的,因为用户可以改变。在初始化阶段,我需要将常量部分分配给结构并保持变量部分不变。当用户修改一个按钮的功能时,我需要覆盖可变部分,保持不变部分不变。

// A structure for the constant part
typedef struct
{
  unsigned char btnID; // this holds the n. of input pin for the button
  unsigned char ledID; // this holds the n. of output pin for the LED
} sBtnConst;

// A structure for the variable part
typedef struct
{
  unsigned char CCnum; // this holds the CC number to send
  unsigned char CCval; // this holds the CC value tu send
} sBtnVar;

// A structure containing all data
typedef struct
{
  sBtnConst c;
  sBtnVar v;
} sButton;

// Declare an array of button structures
// These will contain both the constant and the variable data
sButton Button[4];

// Now initialize a constant structure for the constant part
const sBtnConst cBtnDefinitions[4] =
{
  { 15, 0 },
  { 14, 1 },
  { 10, 8 },
  { 12, 5 },
};

现在,我需要将cBtnDefinitions[]的全部内容复制到Button[]->c如果我这样做了

memcpy(&Button->c, &cBtnDefinitions, sizeof(cBtnDefinitions));

数据按顺序复制到 c 和 v 中,而不仅仅是在成员 c 中。

主循环()中的其余代码如下所示:

void doButton(sButton *btn, unsigned char value)
{
  LitLED(btn->c.ledID, !value);
  SendMidiCC(btn->v.CCnum, btn->v.CCval);
}

// This is a callback function called every time a button has been pushed
void aButtonHasBeenPushed(unsigned char ID, unsigned char value)
{
  unsigned char i;
  for (i=0; i<NUM_OF_BUTTONS; ++i)
    if (i == Button[i].c.btnID)
      doButton(&Button[i], value);
}

当然,我可能有不同类型的按钮,所以我可以将 sButton 结构用于其他目的,并让它们都由相同的函数处理。

【问题讨论】:

  • 您需要将cBtnDefinitions[0]复制到Button[0].c,其他索引(for (int i = 0; i &lt; 4; i++) Button[i].c = cBtnDefinitions[i];)也是如此。
  • 您正在将 4 cBtnDefinitons 复制到只能容纳 1 的位置。

标签: c struct memcpy copying sdcc


【解决方案1】:

您总是需要一个循环,因为源 cBtnDefinitions 是一个连续的内存区域,而目标由 4 个独立的内存区域组成。

您可以使用memcpy

int i;
for (i = 0; i < 4; ++i) {
    memcpy(&Button[i].c, cBtnDefinitions + i, sizeof(sBtnConst));
}

但简单的分配也适用于 GCC:

int i;
for (i = 0; i < 4; ++i) {
    Button[i].c = cBtnDefinitions[i];
}

【讨论】:

  • Button[i].c = cBtnDefinitions[i]; 这不能在 SDCC 上编译。 memcpy 有效,但我希望有一种方法可以复制整个结构而不必使用 for 循环。
猜你喜欢
  • 2021-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-24
  • 1970-01-01
  • 1970-01-01
  • 2011-06-23
  • 2014-10-19
相关资源
最近更新 更多