2015-10-15 58 views
0

我想创建使用Linux的投票功能的程序相同结构的X号。我试图实现一些包含多个民意调查的结构以及一个指向每个民意调查的指针。设置轮询次数没有问题,但是将指针设置为每次轮询都是一个问题。访问在另一个结构

在calloc中,mem返回一个指向内存的指针,但我想使用mem [0]就像指向一块内存的指针,以包含第一个轮询结构和mem [1],就像指向块的指针下一个轮询结构等

struct pollfd已经定义在我的linux包中包含的poll.h中,所以我不需要在我的程序中重新定义它。

如何我保留个人民调结构的存储空间,总只有一个段的内存,而不是每一个结构段的分配?

#include <stdio.h> 
#include <stdlib.h> 
#include <poll.h> 

typedef struct{ 
    long numpolls; 
    struct pollfd* poll; 
}mainrec; 

int main(void){ 
    struct pollfd** mem=calloc(1,sizeof(struct pollfd)*10000); 
    printf("alloc %d\n",sizeof(struct pollfd)*10000); 
    mainrec* rec[10]; 

    rec[0]->numpolls=2; 
    rec[0]->poll=mem[0]; 
    rec[0]->poll[0].fd=2; 
    rec[0]->poll[1].fd=3; 

    rec[1]->numpolls=1; 
    rec[1]->poll=mem[1]; 
    rec[1]->poll[0].fd=2; 

    free(mem); 
    return 0; 
} 
+0

切换到Java :) – javaguest

回答

0

喜欢的东西:

// Allocate an array of 10 pollfds 
struct pollfd *mem = calloc(10,sizeof(struct pollfd)); 
// Get an array of 10 mainrecs 
mainrec rec[10]; 

// Populate the first element of mainrec with two polls 
rec[0].numpolls=2; 
rec[0].poll=mem+0; // points to the first pollfd and the following... 
rec[0].poll[0].fd = ...; 
rec[0].poll[0].events = ...; 
rec[0].poll[0].revents = ...; 
rec[0].poll[1].fd = ...; 
rec[0].poll[1].events = ...; 
rec[0].poll[1].revents = ...; 

// populate the second element of mainrec with a single poll 
rec[1].numpolls=1; 
rec[1].poll=mem+2; // points to the third pollfd 
rec[1].poll[0].fd = ...; 
rec[1].poll[0].events = ...; 
rec[1].poll[0].revents = ...;