C - Access array element by pointer

Description

Access array element by pointer

Demo

#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);
  return 0;//from  w  w w.j  a  va2  s .  com
}

Result

Because p is set to the address of multiple, p + n is essentially the same as multiple + n.

You can see that multiple[n] is the same as *(multiple + n).

Related Topic