繁体   English   中英

在C中为结构中的数组分配顺序存储器地址

[英]Allocating sequential memory addresses for array in structure in C

我想知道如何为另一个结构内的结构数组分配顺序内存。 假设我有struct1,它有一个struct2数组,我想把它全部放在一个连续的内存块中。

我可以使用malloc来分配块,但是如何分配数组的内存?

struct1 *set = malloc(sizeof(struct1) + sizeof(struct2)*number_of_structs);
set->arr = (struct2*)set + sizeof(struct); //This is probably wrong
set->arr[0].data = 1;
set->arr[1].data = 2; 
...

谢谢。

使用灵活的阵列成员

#define NUM_ELEM  42

struct a {
   /* whatever */    
};

struct b {
    int c;
    struct a d[];  // flexible array member
};

struct b *x = malloc(sizeof *x + NUM_ELEM * sizeof x->d[0]);

这种方式在某些Windows API中使用,它可能如下所示:

struct struct1
{
     // some members ...

     struct struct2 arr[1];
}

struct1 *set = malloc(sizeof(struct1) + sizeof(struct2) * (number_of_structs-1));

set-> arr指向number_of_structs成员的数组。 struct1始终在连续内存块中包含至少一个struct2 +其他struct2成员。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM