0

我收到此错误:

错误:从类型“void *”分配给类型“struct sharedMem”时类型不兼容</p>

尝试将结构映射到共享内存时。这是我正在尝试做的事情:

//struct for each card
typedef struct card{
    char c[3]; //card
    char s; //suit
} card;

//struct with player information
typedef struct player{
    int num;
    char* nickname;
    char* FIFO_P;
    struct card* hand;
} player;

//struct for sharedMemory
typedef struct sharedMem{
    unsigned int nplayers;
    unsigned int dealer;
    struct player *players;
    unsigned int roundnumber;
    unsigned int turn;
    struct card *tablecards;
} sharedMem;

然后我有一个功能:

int createSharedMemory(char* shmname,int nplayers){

    int shmfd;
    char SHMNAME[100]={'\0'};
    char *ps;
    ps=&SHMNAME[0];
    strcat(ps,"/");
    strcat(ps,shmname); // name = /shmname
    shmfd = shm_open(SHMNAME,O_RDWR,0755);
    if (shmfd<0){
        if (errno==2){ //File or directory does not exist (shared memory space not created, meaning it's the first process, create the SHMSpace)
            shmfd = shm_open(SHMNAME,O_CREAT|O_RDWR,0755);
            if (shmfd<0){
                perror("Failure in shm_open()");
                fprintf(stderr,"Error: %d\n",errno);
                exit(EXIT_FAILURE);             
            }
        } else {
            perror("Failure in shm_open()");
            fprintf(stderr,"Error: %d\n",errno);
            exit(EXIT_FAILURE);
        }
    }

    struct sharedMem shm;
//  shm.players=malloc(nplayers*sizeof(player));
//  shm.tablecards=malloc(nplayers*sizeof(card));
    ftruncate(shmfd, sizeof(sharedMem));

错误:shm = mmap(0,sizeof(sharedMem),PROT_READ|PROT_WRITE,MAP_SHARED,shmfd,0);

    return 0;

}

有人可以告诉我我做错了什么吗?我认为必须分配属性播放器和桌卡,所以我尝试了 malloc 但没有雪茄。

4

2 回答 2

0
void *mmap(void *addr, size_t len, int prot, int flags,
       int fildes, off_t off);

mmap 返回一个 void 指针,您正试图在结构中收集它。因此,在将其分配给 sharedMem* 之前,在 (struct sharedMem*) 中创建一个结构 sharedMem* 和类型转换 mmap。

于 2013-05-14T11:16:41.690 回答
0

你想要一个指向struct sharedMem

struct sharedMem *shmem = mmap(...);

是时候启动mmap().

于 2013-05-14T11:07:10.840 回答