C - Access array element by pointer


Access array element by pointer


#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  ww . j  ava  2  s. co  m


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