c - 指向 char 数组的指针的内存分配
问题描述
有人可以解释一下
char *names[3]
和
char (*names)[3]
以及如何阅读此运算符?
如果我想动态地为它们分配内存该怎么做?
对于第一种情况,我认为它只是一个char*
长度为 3 的数组,因此没有不适用的内存分配。但是在第二种情况下如何进行内存分配?
解决方案
当遇到这样的问题时,您通常可以求助于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 :-)
+-------+
推荐阅读
- reactjs - 下拉菜单未显示传递数组的值
- c# - 自定义控件的 WPF 设置内容
- javascript - 有没有办法使用 ApexChart 为条形图创建自定义 x 轴标签?
- ios - 运行设备的 watchOS 应用程序时出现“IDELaunchErrorDomain”错误
- android - OnScrollListener 反复调用
- hardware - 今天有没有微处理器使用记分板或 Tomasulo 算法?
- scala - 列为空时 scala 中 Lag 函数的行为
- javascript - 在第一个完成后调用第二个函数
- python - Plotly 中时间序列的 3D 动画
- java - Java ArrayList.remove()