c - 对于 mmaped 结构,静态数组更改为动态

标签 c arrays rtos

我有一个包含这样的数组元素的结构

    #define SIZE 20
    typedef struct
    {
        int currentindex;
        int array[SIZE];
    } tempstruct;

    int main()
    {
        int fd;
        tempstruct *ptr = NULL;
        fd = shm_open("/TESTPROG", O_RDWR | O_CREAT, 0666);
        ptr = mmap(0,sizeof(tempstruct),PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
        /* 
        So in case SIZE is not compile time constant but another int then I do this
        ptr = mmap(0,sizeof(tempstruct),PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
        ptr.array = (int*)malloc(sizeof(int)*SIZE);
    */
        return 0;
    }

如您所见,我使用 mmap 在共享内存区域分配此 tempstruct 的实例,但现在由于一些更改,我想动态分配 的数组元素code>tempstruct 结构作为 SIZE 不会是编译时常量。那么上面的程序仍然有效吗?比如我可以在堆上分配数组,然后 mmap 将其分配到共享内存,这样另一个进程中的数组会指向同一个堆区域吗?我想不会,所以请提出一些更好的方法?

谢谢

最佳答案

下面是解决这个问题的一种方法:

typedef struct
{
    int currentindex;
    int array[0];
}
tempstruct;

int main()
{
    ...
    int totalSize = sizeof(tempstruct) + sizeof(int) * numOfElements;
    ptr = mmap(0, totalSize, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    ...
}

请注意,您将无法正确使用 tempstruct 实例数组。

关于c - 对于 mmaped 结构,静态数组更改为动态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23132031/

相关文章:

c - snprintf + 鹅卵石

c - 如何将 UTC 日期转换为 time_t

没有数字键的PHP array_push

javascript - javascript数组分配错误

c - FreeRtos在ADC任务和Streaming任务中的问题

c - xtaskcreat如何在FREERTOS中创建没有函数体的任务

c - Pthreads 与 OpenMP

Javascript 在具有类的元素上切换类

c - 什么是在 RTOS 中将参数传递给堆栈?

c - 通过递归函数传递分配的数组时出现内存泄漏