当 **p 已经声明时,*p 是什么意思?
short **p = (short **)malloc(sizeof(short *));
(最好写成)
short **p = malloc (sizeof *p);
声明 pointer-to-pointer-to short p 并为带有 malloc 的信号指针分配存储空间并将该内存块的起始地址分配给 p .见:在C语言中,malloc的返回不需要强制转换,没有必要。见:Do I cast the result of malloc?
*p = malloc(sizeof(short));
(相当于)
p[0] = malloc (sizeof *p[0]);
为单个short 分配存储空间,并将该内存块的起始地址分配给p[0]。
**p = 10;
(相当于)
*p[0] = 10;
(或)
p[0][0] = 10;
将值10 分配给取消引用指针*p[0](或**p 或p[0][0]),将该内存地址处的值更新为10。
printf("**p = %d", **p);
打印存储在p[0] 指向的内存块中的值(通过将指针解引用为*p[0] 或**p 访问的值)
保持头脑清醒的方法是,p 是 pointer-to-pointer-to short 类型的单个指针。有 2 级间接(例如 pointer-to-pointer)。要删除一级间接,请使用一元 * 运算符,例如
*p /* has type pointer-to short */
或[..] 也可以作为取消引用,这样:
p[0] /* also has type pointer-to short */
你仍然有一个 pointer-to,所以你必须再移除一层间接来引用存储在指针指向的内存位置的值。 (例如,指针保存short 存储的地址作为其值)。所以你需要:
**p /* has type short */
和
*p[0] /* also has type short */
应该
p[0][0] /* also has type short */
要保持直线的另一部分是 type 控件 pointer-arithmetic。所以p++ 将 8 字节添加到指向指针的地址,因此它现在指向下一个 指针。如果你这样做short *q = (*p)++;(或short *q = p[0]++, adds 2-bytes to the address for the pointer-to-short, soqnow points to the nextshortin the block of memory beginning at*p(orp[0]`)。 (没有第二次短路,因为你只分配了 1 ——但你明白了)
如果您还有其他问题,请告诉我。