如何从实现文件访问头文件中定义的结构?
如何访问 .c
文件中头文件中定义的结构(如 struct common
)?我们将头文件包含在.c
文件中,然后我们就可以直接使用 struct common C;
?
头文件-new_algo.h
#ifndef NEW_ALGO_H_
#define NEW_ALGO_H_
#endif /* NEW_ALGO_H_ */
struct common{
float count;
//other variables
};
main.c <代码>
#include "new_algo.h"
int main()
{
typedef struct common myStruct;
myStruct* S;
S->count = 0;//when I do this segmentation fault occurs
//this is the error I get in eclipse
/* Thread [1] 0 (Suspended : Signal : SIGSEGV:Segmentation fault)
main() at E:/Namratha//trial/.settings/..\\src\\main.c:44 0x401443*/
}
<代码>
How do you access a struct say struct common
, that is defined in a header file, in a .c
file? We'll include the header file in the .c
file and then can we directly usestruct common C;
?
header file-new_algo.h
#ifndef NEW_ALGO_H_
#define NEW_ALGO_H_
#endif /* NEW_ALGO_H_ */
struct common{
float count;
//other variables
};
main.c
#include "new_algo.h"
int main()
{
typedef struct common myStruct;
myStruct* S;
S->count = 0;//when I do this segmentation fault occurs
//this is the error I get in eclipse
/* Thread [1] 0 (Suspended : Signal : SIGSEGV:Segmentation fault)
main() at E:/Namratha//trial/.settings/..\\src\\main.c:44 0x401443*/
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嘿嘿,这个错误不是访问控制造成的。
在使用 struct 变量之前,您应该为其分配空间,例如
myStrcut *s = (myStrcut *)malloc(sizeof(myStruct))
然后分配:
s->count = 0
请尝试一下。
Hey, the fault error is not resulted from access control.
Before use struct varible, you should malloc space for it like
myStrcut *s = (myStrcut *)malloc(sizeof(myStruct))
then assign:
s->count = 0
Please have a try.
是的,这是正确的。只需将标头包含在源文件中并为结构创建实例即可。
header.h
.c
Yes, it's correct. Just include the header in the source file and create the instance for the struct.
header.h
.c