为了解释输出,我评论了代码片段:
#include <stdio.h>
int main()
{
// a is an array of integers
static int a[]={10, 12, 23, 43, 43};
// p is an array of integer pointers. Each of the element, holds address of elements in array "a"
// p[0] = &a[0], p[1] = &a[1], p[2] = &a[2], p[3]=&a[3], p[4]=&a[4]
int *p[]={a, a + 1, a + 2, a + 3, a + 4};
// ptr is a pointer to an integer pointer. Ptr holds base address of array "p"
// ptr = &p[0]
// *ptr = *(&p[0]) = p[0]
// **ptr = *(p[0]) = *(&a[0]) = a[0] = 10
int **ptr = p;
// ptr was pointing to zeroth element in the p array, which is p[0].
// Incrementing pointers, makes it to move by X bytes and hence point to the next element.
// where X = sizeof(int *). int* is p's datatype.
ptr++;
// ptr = &p[1]
// *ptr = *(&p[1]) = p[1]
// **ptr = *(p[1]) = *(&a[1]) = a[1] = 12
// pointer difference is measured by the number of elements
// since ptr points to p+1. difference is 1
printf("ptr - p: %p\n", (void*)(ptr - p) );
// ptr holds address of p+1. *ptr holds value of p[1], which as explained in the above holds address of a[1].
// Hence difference of (a+1) - a is 1
printf("*ptr - a: %p\n", (void* )(*ptr - a));
// ptr holds address of p+1. *ptr holds address of a[1]. **ptr holds value of a[1].
printf("**ptr: %d\n", **ptr);
return 0;
}
有 printf 语句并验证我在程序中提供的注释以便更好地理解。
例如。比较p[0]
和&a[0]
。比较*p[3]
和a[3]
。
希望代码和评论对您有所帮助。
提供的代码是可编译的并且我的屏幕上的输出是
ptr - p: 0x1
*ptr - a: 0x1
**ptr: 12