mmap和struct(不兼容的类型错误struct to void *)

时间:2013-05-14 11:04:08

标签: c struct mmap

我收到了这个错误:

错误:从类型'void *'

类型分配类型'struct sharedMem'时出现不兼容的类型

尝试将struct映射到sharedmemory时。这就是我想要做的事情:

//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但没有雪茄。

2 个答案:

答案 0 :(得分:0)

你想要一个指针struct sharedMem

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

mmap()的{​​{3}}时间。

答案 1 :(得分:0)

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

mmap返回一个void指针,你试图在结构中收集它。所以在将它分配给sharedMem *之前,将一个struct sharedMem *和typecast mmap返回(struct sharedMem *)。