[英]How to see if struct pointer in struct pointer is initialized or not
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:然后在另一个地方我使用一个指针 lmvp (lastmover *) 并做这样的分配:
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;
在程序的第一个游戏移动中,lastmover 变量(玩家 *)被初始化,但分配给 NULL(或垃圾?)的前一个变量
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你只分配指针的大小,这个
lmv.lastmover=malloc(sizeof(player *));
Should be应该
lmv.lastmover=malloc(sizeof(player));
this all works fine
这一切正常
it shouldn't :)它不应该:)
Edit: if you only assign a pointer to lastmover
then 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 to NULL
编辑:如果你只分配一个指向
lastmover
的指针,那么你根本不需要分配内存,否则就是内存泄漏,现在如果你想检查它是否已初始化然后将其初始化为NULL
lastmove lmv = {0};
//or
lmv.lastmover= NULL;
lmv.previous= NULL;
...
//later
if(lmv->previous!=NULL)
A third way to do it, in C99, is using designated initializers:在 C99 中,第三种方法是使用指定的初始值设定项:
lastmove lmv = {
.lastmover= NULL;
.previous= NULL;
};
用这个:
lmv.lastmover=malloc(sizeof(player));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.