【问题标题】:Initializing an array of structure objects, where those objects were previously stored in struct variables初始化结构对象数组,这些对象先前存储在结构变量中
【发布时间】:2019-10-16 15:33:06
【问题描述】:

我定义了一个这样的结构:

struct Profile { 
char name[15]; // Name of profile for displaying to screen later
int numberOfPulses;  // Number of pulses that will occur for one Profile run
int lengthOfPulse;  // Length (uSec) of each pulse produced
int timeBetweenPulses;  // Time (uSec) between consecutive pulse outputs
}

然后,我创建了许多这种结构类型的对象,将每个对象存储在一个适当的变量中。

struct Profile defaultP = {"Default", 1, 100, 0}; 
struct Profile repeat3 = {"Repeat_3", 3, 100, 2000};
struct Profile shortPulse = {"Short_50us", 1, 50, 0};
struct Profile shortPulseRepeat3 = {"Sh_50_R3", 3, 50, 2000};
struct Profile longPulse = {"Single_300", 1, 300, 0};
struct Profile longPulseRepeat3 = {"Sin_300_R3", 3, 300, 2000};
struct Profile custom = {"Custom", 1, 100, 0};

最后,我尝试将这些变量分配给一个数组,这就是我遇到许多错误的地方,包括类型不匹配和/或重新定义等。

struct Profile profileArray[] = {defaultP, repeat3, shortPulse, shortPulseRepeat3, longPulse, longPulseRepeat3, custom};

我真的不明白我做错了什么,但我缺乏经验,并认为这是某种指针问题。 一个重要的注意事项是我必须像我一样单独定义我的 struct Profile 变量,因为它们稍后会在程序中被调用。 谢谢。

【问题讨论】:

  • 请张贴实际错误的样本。
  • 另外请显示此代码的上下文(即它是全局的吗?在函数内部?两者都有?)。
  • 除此之外,您需要在结构定义的末尾使用分号。应该是struct Profile { .... };

标签: c arrays pointers struct initialization


【解决方案1】:

您尝试使用变量的值初始化一个数组。这导致初始化器不是常量的错误。相反,使用:

struct Profile *profileArray[] = {&defaultP, &repeat3, &shortPulse, &shortPulseRepeat3, &longPulse, &longPulseRepeat3, &custom};

现在它是一个指向Profile 结构的指针数组。

注意,对它们的值进行操作现在会改变原始结构中的值,例如:

profileArray[0]->numberOfPulses++;

改变defaultP.numberOfPulses的值

【讨论】:

  • 这是我需要的答案。谢谢保罗。
猜你喜欢
  • 1970-01-01
  • 2016-03-20
  • 2020-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-02
  • 1970-01-01
  • 2018-06-15
相关资源
最近更新 更多