在另一个结构中访问x个相同的结构

时间:2015-10-15 19:15:55

标签: c linux pointers memory struct

我想创建一个使用linux的poll功能的程序。我正在尝试实现一些包含多个民意调查的结构以及指向每个民意调查的指针。设置轮询的数量没有问题,但是将指针设置为每个轮询是一个问题。

在calloc中,mem返回一个指向内存的指针,但是我想使用mem [0]像一个指向一块内存的指针来包含第一个poll结构而mem [1]就像一个指向一个chunk的指针用于下一个poll struct etc。

在我的linux软件包中包含的poll.h中已经定义了

struct pollfd,所以我不需要在我的程序中重新定义它。

如何为每个轮询结构保留内存空间,只分配一个内存段而不是每个结构一个段?

#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;
}

1 个答案:

答案 0 :(得分: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 = ...;
相关问题