你如何在C中构build一个结构体?

我试图制作一个结构数组,其中每个结构代表一个天体,用于我在课堂上正在处理的问题。 我没有那么多的结构体验,这就是为什么我决定尝试使用它们而不是一大堆数组,但是,即使我试图实现这些技术,我仍然遇到许多不同的错误我已经看到了各种线程和stackoverflow(如C和C中的结构数组 – 初始化结构数组 ),但是不是所有的都适用,所以我不能完全复制的方式来做它。 在我告诉你我要做什么之前,只是一个预警,我不能回复几个小时的评论/问题/答案,因为我需要睡觉,因为我已经清醒了太久,我对此感到非常抱歉,但在忙了一天之后,我已经在这个问题上工作了好几个小时,我真的很累。

对于那些已经读过这些东西的人来说,更多的信息是:我不需要任何这种dynamic的东西,我知道/预先确定所有东西的大小。 我也需要这是一个全局数组( gasp GLOBAL VARIABLES ),因为我在几个不同的方法中定义了参数(即GLUT方法)来访问它。

这是我如何定义我的头结构:

struct body { double p[3];//position double v[3];//velocity double a[3];//acceleration double radius; double mass; }; 

在定义结构的内部之前,我定义了其他全局variables的列表,其中一个是这个结构的数组(基本上,如果我在模糊的说话中太模糊了,下面的行高于以上的东西):

 struct body bodies[n]; 

只是你知道, n是我合法定义的东西(即#define n 1 )。

我用了几个不同的方法来使用这个数组,但是最简单和最不耗空间的方法就是我的main方法的简化forms,我初始化了每个结构体中的所有variables,只是在某些variables被设置之前,办法:

  int a, b; for(a = 0; a < n; a++) { for(b = 0; b < 3; b++) { bodies[a].p[b] = 0; bodies[a].v[b] = 0; bodies[a].a[b] = 0; } bodies[a].mass = 0; bodies[a].radius = 1.0; } 

我面临的当前错误是nbody.c:32:13: error: array type has incomplete element type ,其中第32行是我在做的结构数组。

感谢您的任何和所有的帮助,我保证,我会尽快回复你,从现在起12个小时。

最后一个澄清,通过头我的意思是int main(void)上面的空间,但在同一个* .c文件。

 #include<stdio.h> #define n 3 struct body { double p[3];//position double v[3];//velocity double a[3];//acceleration double radius; double mass; }; struct body bodies[n]; int main() { int a, b; for(a = 0; a < n; a++) { for(b = 0; b < 3; b++) { bodies[a].p[b] = 0; bodies[a].v[b] = 0; bodies[a].a[b] = 0; } bodies[a].mass = 0; bodies[a].radius = 1.0; } return 0; } 

这工作正常。 你的问题不是很清楚,所以你的源代码的布局与上面相匹配。

移动

 struct body bodies[n]; 

以后

 struct body { double p[3];//position double v[3];//velocity double a[3];//acceleration double radius; double mass; }; 

rest一切看起来不错。

我想你也可以这样写。 我也是一个学生,所以我理解你的斗争。 有点晚回应,但确定。

 #include<stdio.h> #define n 3 struct { double p[3];//position double v[3];//velocity double a[3];//acceleration double radius; double mass; }bodies[n]; 

所以通过使用malloc()把它们放在一起:

 int main(int argc, char** argv) { typedef struct{ char* firstName; char* lastName; int day; int month; int year; }STUDENT; int numStudents=3; int x; STUDENT* students = malloc(numStudents * sizeof *students); for (x = 0; x < numStudents; x++){ students[x].firstName=(char*)malloc(sizeof(char*)); scanf("%s",students[x].firstName); students[x].lastName=(char*)malloc(sizeof(char*)); scanf("%s",students[x].lastName); scanf("%d",&students[x].day); scanf("%d",&students[x].month); scanf("%d",&students[x].year); } for (x = 0; x < numStudents; x++) printf("first name: %s, surname: %s, day: %d, month: %d, year: %d\n",students[x].firstName,students[x].lastName,students[x].day,students[x].month,students[x].year); return (EXIT_SUCCESS); } 

该错误意味着编译器无法在声明结构数组之前find结构types的定义,因为您说的是在头文件中定义了结构,并且错误在nbody.c然后你应该检查你是否包括正确的头文件。 检查你的#include并确保在声明任何types的variables之前完成struct的定义。