我正在学习C,我在给一个数组赋值给一个属性(codepulses/code)时遇到了问题。
我有一个结构:
typedef struct irPulseSet
{
int pulseCount;
int pulses[][2];
} 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 }
};
然后将数组分配给
upButton.pulses = upButtonPulses;
但是当我编译时,我得到了一个错误:
灵活数组成员的使用无效
我在这里做错了什么?
您必须将结构中的脉冲成员的类型更改为指向2D数组的指针,然后才有一个灵活的数组成员,您已经动态地分配了它。
typedef struct irPulseSet
{
int pulseCount;
int (*pulses)[2]; //pointer to a 2d array
} irPulseSet;
要设置成员,请执行相同的操作:
upButton.pulses = upButtonPulses;
或者一种更聪明的方法来初始化结构
irPulseSet upButton = { 31 , upButtonPulses } ;
我在这里做错了什么?
null
灵活数组成员的使用无效
出现此错误的原因是,要使用灵活的数组成员,必须为数组分配额外的空间,例如当irPulseSet upButton = malloc(sizeof(irPulseSet) + sizeof(upButtonPulses));
memcpy(upButton->pulses, upButtonPulses, sizeof(upButtonPulses));
错误是由于
int pulses[][2];
你需要定义大小!!试一次。