首页 > 解决方案 > 指向 char 数组的指针的内存分配

问题描述

有人可以解释一下

char *names[3] 

char (*names)[3] 

以及如何阅读此运算符?
如果我想动态地为它们分配内存该怎么做?

对于第一种情况,我认为它只是一个char*长度为 3 的数组,因此没有不适用的内存分配。但是在第二种情况下如何进行内存分配?

标签: c

解决方案


当遇到这样的问题时,您通常可以求助于cdecl(在线版本here):

cdecl> explain char *names[3]
declare names as array 3 of pointer to char

cdecl> explain char (*names)[3]
declare names as pointer to array 3 of char

所以前者创建了三个指向字符的指针的数组:

+----------+
| names[0] | -> char
|      [1] | -> char
|      [2] | -> char
+----------+

后者创建一个指向大小为 3 的 char 数组的单个指针。

+-------+
| names | -> char, char, char - no, not a dance step :-)
+-------+

推荐阅读