简体   繁体   English

指针数组Malloc(C编程)

[英]Pointer Array Malloc (C Programming)

I found this one line that I don't understand. 我发现我不理解这一行。 It says 它说

char (*storage)[15] = malloc(sizeof *storage * 8)

Does anybody know what this is mean? 有人知道这是什么意思吗? why I see a lot of * ? 为什么我看到很多*

I don't get it because why he/she multiplied by 8 (it seems like that) but then declared it was [15] too? 我不明白这是因为为什么他/她乘以8(看起来是这样),然后又宣布也是[15]

Correct me if I'm wrong. 如果我错了纠正我。

char (*storage)[15] = malloc(sizeof *storage * 8)

It allocates memory for 8 character arrays of size 15 . 它为大小为15 8字符数组分配内存。

For all * you ask- 对于所有*您问-

char (*storage)[15]              // pointer to array of 15 chars 

and this - 和这个 -

sizeof *storage * 8   // this is 8 times sizeof type to which storage points 

char (*storage)[15] is a pointer to 15-element array of char . char (*storage)[15]char 15个元素的数组的指针。

sizeof *storage * 8 is 8 times the size of the type at which storage points. sizeof *storage * 8storage点类型的大小的8倍。

char (*storage)[15] = malloc(sizeof *storage * 8);

dynamically allocates an 8x15 array of char . 动态分配一个8x15的char数组。 This is roughly similar to writing 这大致类似于写作

char storage[8][15];

except that 除了那个

  • The lifetime of a dynamically-allocated object lasts until it is explicitly deallocated with free , whereas the lifetime of an automatically-allocated object lasts until the program exits the object's enclosing scope; 动态分配对象的生命周期一直持续到用free显式释放它为止,而自动分配对象的生命周期一直持续到程序退出该对象的封闭范围为止。
  • The storage for a dynamically-allocated object is (usually) taken from a different memory segment than automatically-allocated objects; 动态分配对象的存储空间(通常)通常与自动分配对象的存储区不同。
  • You can extend the size of a dynamically-allocated array as necessary. 您可以根据需要扩展动态分配的数组的大小。 IOW, if you realized you needed two more rows, you could write IOW,如果您意识到还需要两行,则可以编写
     size_t curRows = 8; char (*tmp)[15] = realloc( storage, sizeof *storage * (curRows + 2)); if ( tmp ) { storage = tmp; curRows += 2; } 
    You can't do that with an automatically-allocated array. 您不能使用自动分配的数组来做到这一点。

An alternate way of dynamically allocating an 8x15 array is something like this: 动态分配8x15数组的另一种方法是这样的:

char **storage = malloc( sizeof *storage * 8 );
if ( storage )
{
  for ( size_t i = 0; i < 8; i++ )
  {
    storage[i] = malloc( sizeof *storage[i] * 15 );
  }
}

Note that all three versions can be indexed as storage[i][j] . 注意,所有三个版本都可以索引为storage[i][j]

The main advantage of the last method is that each row can be different lengths if you want them to be. last方法的主要优点是,如果您希望每行的长度可以不同。 The main disadvantages are that the rows won't necessarily be adjacent in memory, and you have to free each storage[i] before you can free storage . 主要缺点是行在内存中不一定会相邻,因此必须先free每个storage[i]然后才能free storage

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

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