【问题标题】:accessing x number of same structs in another struct在另一个结构中访问 x 个相同的结构
【发布时间】: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


    【解决方案1】:

    类似:

    // 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 = ...;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多