How to access a structure defined in a header file from an implementation file?
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 use
struct common C;
?
header file-new_algo.h
#ifndef NEW_ALGO_H_
#define NEW_ALGO_H_
#endif /* NEW_ALGO_H_ */
struct common开发者_StackOverflow中文版{
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*/
}
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.
Yes, it's correct. Just include the header in the source file and create the instance for the struct.
header.h
struct common
{
// ...
};
.c
#include "header.h"
struct common C ;
精彩评论