简体   繁体   中英

Global Char Pointer (C Programming)

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 ?

You should use a struct , if the variables make up an object. If they do:

struct myTrialStruct{
    char *trialOne;
    char *trialTwo;
    char *trialThree;
} myGlobalVar;

Just write this at the top of your source file. myGlobalVar is a global variable of type struct myTrialStruct .

Or if the three variables are part of a sequence use an array:

char *myGlobalArr[3];  // array of char *

Using a struct won't increase the chance of segfault; careless pointers will.

And try to limit the use of global variables. Your code will become very disorganized, and it will be harder to fix bugs.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM