C语言中外部函数修改结构数组
我是C语言的新手,所以我希望在这里尽可能多地学习外部函数、指针和结构 我的想法是:创建一个结构数组,然后编写“外部”函数(即保存在与主程序不同的文件中的函数),我可以使用这些函数修改结构数组中结构中的字段 我的努力:C语言中外部函数修改结构数组,c,arrays,pointers,struct,C,Arrays,Pointers,Struct,我是C语言的新手,所以我希望在这里尽可能多地学习外部函数、指针和结构 我的想法是:创建一个结构数组,然后编写“外部”函数(即保存在与主程序不同的文件中的函数),我可以使用这些函数修改结构数组中结构中的字段 我的努力: extern void fillMass(Body *p, int size) typedef struct body Body; int main() { body bodies[n] /* creates an array of structures of type b
extern void fillMass(Body *p, int size)
typedef struct body Body;
int main() {
body bodies[n] /* creates an array of structures of type body (yes this is a hw problem) */
int sizeBodies = sizeof(bodies)/sizeof(struct body);
Body *planets;
planets = &bodies[0];
fillMass(planets, sizeBodies);
}
当我在Main下面定义了fillMass时,它就起作用了。但是我想在另一个文件中定义它,所以我试着制作fillMass.h(我首先使用fillMass.c,但后来发现了很多这样的例子,人们使用include语句来包含他们的外部函数,我想这需要一个.h文件…?或者这只是一个约定?所以我写了一个简单的文件,名为fillMass.h
void fillMass(Body* p, int size) { /* this is line 10 of the code */
p[0].mass=99;
p[1].mass=350; /*just testing, not using size parameter */
}
但这不起作用。我得到了错误
fillMass.h:10: error: expected ‘)’ before ‘*’ token
有什么想法吗?这是fillMass.h的一个问题;当我完成这项工作时,我应该能够毫不费力地完成我开始要做的事情吗?
感谢阅读。添加一个“,质量=99。在C中,您可以选择 使用typedef声明结构
typedef struct body{
int mass;
}Body;
然后是函数:
void fillMass(Body *p, int size)
或不键入结构定义
struct body{
int mass;
};
然后该函数将是:
void fillMass(struct body *p, int size)
两个文件
body.h
struct body{
int mass;
//other elements
};
typedef struct body Body;
void fillMass(Body* p, int size) { /* this is line 10 of the code */
p[0].mass = 99;
p[1].mass = 350; /*just testing, not using size parameter */
}
main.c
#include "body.h"
int main() {
const unsigned n = 5;
//you should determine n
Body bodies[n]; /* creates an array of structures of type body (yes this is a hw problem) */
int sizeBodies = sizeof(bodies) / sizeof(Body);
body *planets;
planets = bodies; //the same as &bodies[0]
fillMass(planets, sizeBodies);
return 0;
}
Tha意味着当编译器到达fillMass.h的第10行时,
Body
未定义。您必须在“p[0].mass=99”之后定义fillMass.hsemicolon中的结构Body
。此外,您还将其标记为c
和c++
,但它们是不同的语言。在这两种语言中,身体都不是合法的,应该是身体代码>。请复制粘贴您的代码或仔细检查键入的错误@MattMcNabb,在C++ <代码>体[n];<事实上,如果存在struct body
,则code>将起作用。他的代码没有尾随分号,因此编译器将看到body body[n]int sizeBodies…
,这是一个语法错误。而且,它是否与分号一起工作取决于什么是<代码> N>代码>,构建数组不能在C++中运行时大小(尽管它是允许编译器的通用编译器扩展)。当我尝试编译体H时,我会听到一个关于“未定义的指向主引用”的抱怨。帮助?谢谢亲爱的user2198121给了我一些我能理解的东西。我现在正在改变一种新的编码方式——我所有与“body”相关的东西(结构定义、方法等)都在“body.h”中,我在main.cpp中使用它们。@blaughli,对不起,我肯定是指“main.c”。不过,你应该确定你是用C或C++编程的。