2

我见过像这样为结构分配内存

   ///enter code here
   for(i = 0; i<10; i++)
     s->a[i].mem = malloc(sizeof(*a[0]));

这是什么意思???它正在为a或mem分配内存。我很困惑。

如果它分配给指针mem?我在代码中看到了,他们通过

mem[0] = bla...bla...
mem[1] = bla...bla...

是否合法???

4

4 回答 4

3

a[]应该是一个结构数组,其中每个都a[i]表示一个结构。

在结构mem中应该是结构类型的指针(自指向)。所以表情。

s->a[i].mem = malloc(sizeof(*a[0])); 

使用 malloc 动态分配内存并将地址分配给mem

就像是:

struct  xyx{
   int data;
   struct  xyx   *mem;
};

 struct  xyx a[10];

所以:a[0]的类型struct xyx

和表达:

a[i].mem = malloc( sizeof(*a[0])); 

如同:

a[i].mem = malloc( sizeof(struct xyz); 

第二: 现在,什么是 s->a[i]

s又是一个其他结构类型的指针变量,其中有一个 struct 类型的a[]数组xyz。就像是:

struct abc{ 
  struct  xyx a[10];
}; 

应该s是:

struct abc  x;
struct abc  *s = &x;

或内存s应该动态分配。所以s -> a[i]要访问成员。

所以表达:

s -> a[i].mem =  malloc(sizeof(*a[0]));
^    ^     ^ 
|    |     is pointer to struct of type that same as type of a[0]   
|    array of struct's elements,    
s is pointer to a struct in which `a[]` is datamember  
于 2013-07-23T10:47:59.007 回答
1

This will allocate memory of size *a[0] and pointer to the start of this memory block will be saved in mem pointer.

于 2013-07-23T10:44:06.560 回答
0

It means allocate a block of memory the same size as the thing that a[0] points to

This memory allocation is pointed to by s->a[i].mem

So, I'd guess that elsewhere in the program a[0] is set up and then this fragment uses the contents of a[0] to find the size for the other members of a[]

于 2013-07-23T10:45:51.030 回答
0

a[0]该代码分配了一个与指向的对象具有相同大小的块。然后它将指向该块的指针存储在s->a[i].mem.

于 2013-07-23T10:43:55.950 回答