I have a struct like the following:
typedef struct {
player *lastmover;
player *previous;
} lastmove;
typedef struct {
int moves;
char *name;
} player;
I try do a memory alloc like this so the :
lastmove lmv;
lmv.lastmover=malloc(sizeof(player *));
lmv.previous=malloc(sizeof(player *));
.....
callfunction(&lmv);
.....
then in another place i use a pointer lmvp (lastmover *) and do assignment like this:
void
callfuntion(lastmove *)
{
.....
lmvp->previous=lmvp->lastmover;
lmvp->lastmover=p; //where p is of type (player *)
.....
}
this all works fine, but I don’t know how to control weather previous mover is initialized. In the first game move in the program the lastmover variable (player *) is initialized, but the previous variable that is assigned to NULL(or garbage?) lmvp->previous=lmvp->lastmover;. But I want somehow to check if the previous mover is initialized or not. Im trying this:
void
callfunction(lastmove *)
{
......
......
if(lmvp->previous!=NULL)
......
}
But im quite certain it will not do.. How is the best way to control this?
you’re only allocating size of pointer, this
Should be
it shouldn’t 🙂
Edit:
if you only assign a pointer to
lastmoverthen you don’t need to allocate memory at all, otherwise it’s a memory leak, now if you want to check if it’s initialized then initialize it toNULLA third way to do it, in C99, is using designated initializers: