c - 初始化一个结构对象数组,这些对象之前存储在结构变量中

标签 c arrays pointers struct initialization

我定义了这样一个结构:

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/

相关文章:

C - 通过指针从函数获取结构 - 段错误

c - C中通过指针修改函数中数组的值

c++ - 复制一个指针,改变拷贝指向的内容而不改变原始指针?

c - 关于 C 中 struct of struct 的信息

c - Gtk,模态对话框

c - OpenCL CLK_LOCAL_MEM_FENCE 导致中止陷阱 6

c# - C# 中的数组写入是原子的吗?

c++ - 无符号字符数组与指针参数不兼容

调用同一个程序实例?

JavaScript - 使用 for 循环过滤带有参数的数组