rmalizia44 rmalizia44 - 3 years ago 166
C Question

Struct is being filled with zeros in C

i have the following code:

.h file:

typedef struct subsystem
const char* name;
SDL_bool (*fun_init)();
SDL_bool (*fun_updt)();
SDL_bool (*fun_quit)();
void (*fun_poll)(SDL_Event* event);
} subsystem_t;

subsystem_t audio_subsystem;

.c file:

SDL_bool audio_init()
SDL_Log("Audio Init");
return SDL_TRUE;

SDL_bool audio_quit()
SDL_Log("Audio Quit");
return SDL_TRUE;

subsystem_t audio_subsystem = {"Audio", audio_init, NULL, audio_quit, NULL};

When the program runs, audio_subsystem has the following data (with some log function):

(null) :: 00000000 :: 00000000 :: 00000000 :: 00000000

at runtime, name is NULL and all function pointers are NULL too, I don't know why it's happening, c compiler is filling my struct with zeros.

This is the log function:

SDL_Log("%s :: %p :: %p :: %p :: %p", subsystem->name, subsystem->fun_init, subsystem->fun_updt, subsystem->fun_quit, subsystem->fun_poll);


Adding extern keyword before subsystem_t audio_subsystem solved my
problem, i thought it was default lol. Thanks everyone who helped,
love you guys!

Answer Source

This line in your header file:

subsystem_t audio_subsystem;

is not just a declaration, it is a definition of a static variable at file scope, which will be initialised with zero values. In addition, each compilation unit that includes the header will define its own audio_subsystem.

Apparently, your C file doesn't include its header, otherwise this line:

subsystem_t audio_subsystem = {"Audio", audio_init, NULL, audio_quit, NULL};

would be flagged a redefinition of the same symbol.

To fix your error, you could mark the variable in the header as declaration with the extern keyword:

extern subsystem_t audio_subsystem;

This just declares a variable without data. Users of your header file know that there is such a variable and the variable itself is defined (with proper initialisers) in your C file.

(But perhaps you can find a better design that doesn't require to share global variables. It is also good practice that C files should include their own headers to catch such mistakes.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download