I'm just getting started to learn C language by creating small programs.
Now, I'm in the middle of creating a program that require either struct or something global, because later on somewhere in my function I just want to call them directly.
I prefer not to use struct because I'm afraid that it will increase the chance of seg. fault somewhere between lines of code.
My question is: Are these two the same?
struct myTrialStruct{
char *trialOne;
char *trialTwo;
char *trialThree;
};
and
extern char *trialOne;
extern char *trialTwo;
extern char *trialThree;
char *trialOne;
char *trialTwo;
char *trialThree;
If not, can somebody tell me the proper way to create a global char pointer without having me to create a struct?
If you have one compilation unit then it is enough to place these declarations outside any function.
char *trialOne;
char *trialTwo;
char *trialThree;
If you are going to have several compilation units that will access these pointers then you should to place these declarations in a header
extern char *trialOne;
extern char *trialTwo;
extern char *trialThree;
and in some module to place these definitions of the pointers
char *trialOne;
char *trialTwo;
char *trialThree;
The header should be included in any compilation unit that need to access these pointers.
As for your question
Are these two the same?
then these
struct myTrialStruct{
char *trialOne;
char *trialTwo;
char *trialThree;
};
a type declaration that is it is a structure declaration, no object is created.
while these are object declarations
char *trialOne;
char *trialTwo;
char *trialThree;
You could define an object of the structure type for example the folloiwng way
struct myTrialStruct{
char *trialOne;
char *trialTwo;
char *trialThree;
};
struct myTrialStruct hlobal_pointers;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With