0

this is a program from a book in C

#include<stdio.h>

int *fun(int *p, int n);

main()
{
    int arr[10]={1,2,3,4,5,6,7,8,9,10}, *ptr, n;
    n=5;
    ptr = fun(arr, n);
    printf("arr = %p, ptr = %p, *ptr = %d\n",arr,ptr,*ptr); 
}
int *fun(int *p, int n)
{
    p=p+n;
    return p;
}

I'm confused as to how p=p+n line works, as p should hold the pointer towards arr[0] according to me, but it adds with an integer and in output *ptr is 6

1 Answers1

1

The integer that is summed represents the element in the array at the summed value. For example: arr [8] is equivalent to * (i + 8), with char * i = (char *) arr, in this case I will jump to element 8 of the array (if for example the array is char).

Note that arrays are nothing more than pointers.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Loris Simonetti
  • 217
  • 2
  • 10