如何通过指针访问数组元素?参考以下代码:
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <string.h>
int main(void)
{
char multiple[] = "a string";
char *p = multiple;
for (int i = 0; i < strnlen_s(multiple, sizeof(multiple)); ++i)
printf("multiple[%d] = %c *(p+%d) = %c &multiple[%d] = %p p+%d = %p\n", i, multiple[i], i, *(p + i), i, &multiple[i], i, p + i);
system("pause");
return 0;
}
执行上面示例代码,得到以下结果:
multiple[0] = a *(p+0) = a &multiple[0] = 00AFF81C p+0 = 00AFF81C
multiple[1] = *(p+1) = &multiple[1] = 00AFF81D p+1 = 00AFF81D
multiple[2] = s *(p+2) = s &multiple[2] = 00AFF81E p+2 = 00AFF81E
multiple[3] = t *(p+3) = t &multiple[3] = 00AFF81F p+3 = 00AFF81F
multiple[4] = r *(p+4) = r &multiple[4] = 00AFF820 p+4 = 00AFF820
multiple[5] = i *(p+5) = i &multiple[5] = 00AFF821 p+5 = 00AFF821
multiple[6] = n *(p+6) = n &multiple[6] = 00AFF822 p+6 = 00AFF822
multiple[7] = g *(p+7) = g &multiple[7] = 00AFF823 p+7 = 00AFF823
因为p
被设置为multiple
地址,所以p + n
基本上与多个+ n
相同。可以看到multiple[n]
与*(multiple + n)
相同。