Spade Johnsson
Spade Johnsson

Reputation: 572

Pointers to structures and memory allocation in C

Got 2 things here to which I can't seem to find an answer... I am working on a project for the university where we (we're 3) are developing the entire Client side of a board game (e.g. server communication and A.I.). Now our big presentation is coming up, and I can't seem to get in touch with any my mates for the past 2 days...

Our entire program is up and running without any issues, but there are 2 definitions/declarations I don't totally get.

In a globals.h we define multiple structures, which we use in different .c files, and especially in our main.c file.

As a global variable, we declare

Game* GAME = (Game*) -1;

in our main.c. Game* is a struct we defined in our global header file, however... What does this exactly do? we create a pointer GAME of type Game, but what does the '(Game*) -1;' do? does it set all components of the structure to '-1'? does this declared GAME structure get sizeof(Game) allocated of memory or the size of the pointer, or [...]? If not, How much does the declaration allocate memory?

The second statement is declared inside the main.c as a local variable:

Config* config;

where Config also refers to a struct in our globals header. Does our pointer config of type Config get any memory allocated at this point? Does the system set all values to some sort of default, or... ?

Thanks!

Upvotes: 2

Views: 188

Answers (3)

arin1405
arin1405

Reputation: 677

I would like to add that you can allocate memory and point it in this way:

GAME = (Game*)malloc(sizeof(Game));

Malloc returns a void pointer (void*), which can be cast to the desired type of data pointer (in this case, it is Game*) in order to be dereferenceable.

Upvotes: 0

eyalm
eyalm

Reputation: 3366

Game* GAME = (Game*) -1;

This is only the declaration of a global variable. It is assigned with an invalid pointer just to make sure later it was initialized. It is better to set it to NULL. It is probably initialized in another place. I would expect the following:

in globals.h:

extern Game* GAME; // Making this global variable shared between files

in globals.c (or somewhere else)

Game* GAME = (Game*) -1; // Just an invalid initialization

in main.c (or somewhere else):

GAME = malloc(sizeof(Game)); // Allocate memory and point to it
if (!GAME)
    error

Upvotes: 1

fede1024
fede1024

Reputation: 3098

Game* GAME = (Game*) -1;

1) You just declare a pointer, you don't allocate a structure, you just set it to -1 (probably it would be better to put it to NULL).

Config* config;

2) No, it does not take memory, also this one is just a pointer.

Pointer are just variables that contain addresses of memory locations, no real allocation is performed.

Upvotes: 4

Related Questions