Curious Guy 007
Curious Guy 007

Reputation: 571

How to access Global Variables in C

I am trying to populate global variables but it seems to not be working . Here is my code .

typedef struct Global_ {

char values[3][40]

}Global_t;
//function file

GBL_PTR = calloc (1, sizeof (Global_t));
memset(GBL_PTR.values,'\0',sizeof(GBL_PTR.values));

//opening a file and reading it

sscanf(linebuf, "List of values %s , %s \n",
               GBL_PTR.values[0],
               GBL_PTR.values[1]);
printf("Why dont i see these logs %s",GBM_PTR.values[1]);

I don't see any crashes , just no logs. The compiles fine. I am new to C, can someone let me know what am I missing here. The main idea is to access a global variable from my function. How do I do it?

Upvotes: 0

Views: 108

Answers (2)

BlackMamba
BlackMamba

Reputation: 10252

There some errors in you code, (1) you miss a semicolon after char values[3][40]

(2) the return type of calloc is void*, so use Global_t* GBL_PTR = (Global_t*)calloc (1, sizeof (Global_t));

(3) because the type of GBL_PTR is an pointer, so you can access values like this:GBL_PTR->values or (*GBL_PTR)values.

typedef struct Global_ {

    char values[3][40];

}Global_t;
//function file

Global_t* GBL_PTR = (Global_t*)calloc (1, sizeof (Global_t));
memset(&(GBL_PTR->values),'\0',sizeof(GBL_PTR->values));

//opening a file and reading it
char* linebuf= "List of values wang , yang \n";
sscanf(linebuf, "List of values %s , %s \n",
    GBL_PTR->values[0],
    GBL_PTR->values[1]);
printf("Why dont i see these logs %s\n", GBL_PTR->values[1]);

Upvotes: 1

SzG
SzG

Reputation: 12629

You forgot the type of GBL_PTR, it should be:

Global_t *GBL_PTR = calloc(1, sizeof (Global_t));

GBL_PTR is a pointer so use the ->operator instead of the . operator everywhere.

GBL_PTR->values
GBL_PTR->values[0]

etc...

Upvotes: 1

Related Questions