Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Char Pointer (C Programming)

Tags:

c

pointers

struct

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?

like image 307
John Avatar asked Feb 08 '23 16:02

John


1 Answers

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;
like image 162
Vlad from Moscow Avatar answered Feb 19 '23 20:02

Vlad from Moscow