2015-10-15 47 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 = ...;