我定义了这样一个结构:
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 *profileArray[] = {&defaultP, &repeat3, &shortPulse, &shortPulseRepeat3, &longPulse, &longPulseRepeat3, &custom};
现在它是指向 Profile
结构的指针数组。
请注意,对它们的值进行操作现在将更改原始结构中的值,例如:
profileArray[0]->numberOfPulses++;
更改defaultP.numberOfPulses
的值
关于c - 初始化一个结构对象数组,这些对象之前存储在结构变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58416943/