简体   繁体   中英

How to assign to a struct pointer in another struct pointer

Im having trouble assigning to struct pointer in another struct pointer

The structs looks like this:

header.h

typedef struct {
    int drawnlines;
    char *name;
} player;

typedef struct {
    char a, b;
    p *mover;
    p *previous;
} lastmove;

In another function Im calling another function that is supposed to change a pointer to this struct, this is also the function that gives me an warning:

program.c

#include header.h
.....
lastmove lmv;
lmv.mover=malloc(sizeof(player *));
lmv.previous=malloc(sizeof(player *));
player p;
p.drawnlines=0;
p.drawnlines=0;
strcpy(p.name, "patrik");
function(&lmv, &p);

.....
int
function(lastmove *lmv, player *p)
{
    lmv->a='b';
    lmv->b='a';
    lmv->previous=lmv->mover;
    lmv->mover=p;        // warning: assignment from incompatible pointer type
}

What is wrong in my code?

UPDATE: Now the code works, was a simple mistake. The struct "lastmove" is now changed to

typedef struct {
    char a, b;
    player *mover;
    player *previous;
} lastmove;

Well, in your code, mover is a pointer to type p , which isn't defined anywhere - do you mean this?

typedef struct {
    char a, b;
    player *mover;
    player *previous;
} lastmove;

Also, I think there's an issue with your allocation. You're allocating enough space for a player* , which is a pointer to a player, when what you need is enough space for a player .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM