【问题标题】:Cannot assign array to struct property无法将数组分配给结构属性
【发布时间】:2014-06-04 00:03:51
【问题描述】:

我刚刚学习 C,但在将数组分配给属性时遇到问题 (pulses)。

我有一个结构:

typedef struct irPulseSet
{
    int pulseCount;
    int pulses[][2];
} irPulseSet;

我使用上面创建的irPulseSet 类型创建一个新变量,并定义一个数组:

irPulseSet upButton;

upButton.pulseCount = 31;
int upButtonPulses[31][2] = 
{
    { 0 , 120 },
    { 440 , 360 },
    { 440 , 340 },
    { 440 , 1120 },
    { 420 , 380 },
    { 420 , 360 },
    { 400 , 1140 },
    { 420 , 1120 },
    { 420 , 380 },
    { 420 , 1140 },
    { 420 , 1120 },
    { 440 , 340 },
    { 440 , 360 },
    { 440 , 1120 },
    { 440 , 1120 },
    { 420 , 1120 },
    { 400 , 1140 },
    { 420 , 360 },
    { 440 , 340 },
    { 440 , 360 },
    { 440 , 1140 },
    { 440 , 360 },
    { 440 , 340 },
    { 440 , 380 },
    { 420 , 360 },
    { 440 , 1120 },
    { 440 , 1120 },
    { 440 , 1120 },
    { 440 , 27400 },
    { 7160 , 1500 },
    { 0 , 0 }
};

然后我将该数组分配给 irPulseSet 结构中的一个属性。

upButton.pulses = upButtonPulses;

但是当我编译时,我得到了错误:

灵活数组成员的使用无效

我在这里做错了什么?

【问题讨论】:

标签: c arrays struct


【解决方案1】:

错误原因

int pulses[][2];

你需要定义尺寸!!试一次。

【讨论】:

  • 做整数脉冲[31][2];然后编写一个函数将 upButtonPulses[31][2] 复制到 int pulses[31][2];在结构 irPulseSet
【解决方案2】:

我在这里做错了什么?

您正在对数组类型进行分配 (=)。 如果您希望结构和数组都指向内存中的同一位置,请参阅self. 的答案指向正确的方向。但是,如果您想要一份数据副本,请继续阅读。


灵活数组成员的使用无效

您收到此错误的原因是,要使用灵活的数组成员,您必须为数组分配额外的空间,例如当您 malloc'd 时。例如。

irPulseSet upButton = malloc(sizeof(irPulseSet) + sizeof(upButtonPulses));
memcpy(upButton->pulses, upButtonPulses, sizeof(upButtonPulses));

【讨论】:

    【解决方案3】:

    您必须将结构中的脉冲成员的类型更改为指向二维数组的指针,然后才能拥有动态分配的灵活数组成员。

    typedef struct irPulseSet
    {
        int pulseCount;
        int (*pulses)[2];  //pointer to a 2d array
    
    } irPulseSet;
    

    要设置成员,您也可以这样做:

    upButton.pulses = upButtonPulses;
    

    或者更聪明的方式来初始化结构体

    irPulseSet upButton = { 31 , upButtonPulses } ;
    

    【讨论】:

    • @LeeDuhem 括号是不必要的。
    • @LeeDuhem 是的;不;运算符优先级使它们变得不必要。
    • 是的,你是对的,那些括号不是必需的。我在测试时又犯了一个错误。
    • 谢谢!还有一件事:*pulses 周围的括号是什么?我知道在声明指针时使用 *,但不确定括号。
    • 你将有一个整数指针数组,没有括号。
    猜你喜欢
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 2018-12-07
    • 1970-01-01
    • 2011-12-07
    相关资源
    最近更新 更多