在 C 中创建结构体数组?
可能的重复:
在 C 中定义结构体数组?
我有一个结构体 DATA ,它有两个字段(int - id 和 char - dat)。
我为其分配内存:
DATA *current = malloc(sizeof(DATA));
并分配所有字段:
current->id = 1;
current->dat = a;
我不知道该怎么做...是如何将我刚刚初始化的 DATA 添加到 DATA 数组中(声明为 DATA lstData[100])
另外,通过询问之前的问题,我觉得在这种情况下我可能不需要 malloc,因为我有一个包含 100 个 DATA 元素的静态数组?在这种情况下,以下代码将失败:
lstProc[10]->id = 1; //Error: Program received signal: "EXC_BAD_ACCESS"
Possible Duplicate:
Defining an array of structures in C?
I have a structure DATA which has two fields (int - id and char - dat).
I allocate memory to it:
DATA *current = malloc(sizeof(DATA));
And assign all the fields:
current->id = 1;
current->dat = a;
What I am not sure how to do...is how to add the DATA I just initialized into an array of DATA (which is declared as DATA lstData[100])
Also, from asking previous questions, I feel like maybe I don't need to malloc in this case since I have a static array of 100 DATA elements? In that case, the following code fails:
lstProc[10]->id = 1; //Error: Program received signal: "EXC_BAD_ACCESS"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你是对的。无需进行 malloc。由于您有一个结构数组(不是指向结构的指针),因此请使用:
You are right. No need to malloc. Since you have an array of structures (not pointers to structures), use:
如果您有 DATA 结构的静态数组,而不是指向 DATA 的指针,则需要使用点来访问特定的 DATA 成员:
并回答您原来的问题:
If you have static array of DATA structures, NOT of pointers to DATA, you need to use dot to access particular DATA members:
And answer to your original question: