【发布时间】:2015-10-15 19:15:55
【问题描述】:
我想创建一个使用 linux 的 poll 功能的程序。我正在尝试实现一些包含许多民意调查的结构以及指向每个民意调查的指针。设置 poll 的次数没问题,但是设置每个 poll 的指针是个问题。
在 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;
}
【问题讨论】:
标签: c linux pointers memory struct