[英]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 * 8
是storage
点类型的大小的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 除了那个
free
, whereas the lifetime of an automatically-allocated object lasts until the program exits the object's enclosing scope; 动态分配对象的生命周期一直持续到用free
显式释放它为止,而自动分配对象的生命周期一直持续到程序退出该对象的封闭范围为止。 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.