The problem is that within the condition of the loop you are using the pointer that is changed within the loop.
while ( p < p+n ){
printf("Sum of array is %d\n",sum);
sum += *p++;
}
So the condition never will be equal to false except when n is equal to 0.
The function can be declared and defined the following way
long long int sum_array( const int *p , size_t n );
Pay attention to that within the function the array is not changed. So the first parameter should have the qualifier const.
And
long long int sum_array( const int *p , size_t n )
{
long long int sum = 0;
for ( const int *q = p; q < p + n; ++q )
{
sum += *q;
}
return sum;
}
If you want to use the while loop then the pointer q need to be defined outside the loop
const int *q = p;
while ( q < p + n )
{
sum += *q++;
}
Also do the following changes
#define LEN(a) (sizeof(a)/sizeof(a[0]))
and
printf("Array length %zu\n",LEN(a));
long long int sum = sum_array(a,LEN(a));
printf( "Sum of array is %lld\n",sum);
The type long long int is used for the variable sum because in general there can be an overflow.
Consider for example the following demonstrative program
#include <stdio.h>
#include <limits.h>
#define LEN(a) (sizeof(a)/sizeof(a[0]))
int sum_array( const int * , size_t );
int main(void)
{
int a[] = { INT_MAX, 1 };
printf("Array length %zu\n",LEN(a));
int sum = sum_array( a, LEN( a ) );
printf("Sum of array is %d\n",sum);
return 0;
}
int sum_array( const int *p , size_t n )
{
int sum = 0;
const int *q = p;
while ( q < p + n )
{
sum += *q++;
}
return sum;
}
Its output is
Array length 2
Sum of array is -2147483648
It is evident that the result is not what you are expecting.
If to make the type of the variable sum long long int then the result will be correct.
#include <stdio.h>
#include <limits.h>
#define LEN(a) (sizeof(a)/sizeof(a[0]))
long long int sum_array( const int * , size_t );
int main(void)
{
int a[] = { INT_MAX, 1 };
printf("Array length %zu\n",LEN(a));
long long int sum = sum_array( a, LEN( a ) );
printf("Sum of array is %lld\n",sum);
return 0;
}
long long int sum_array( const int *p , size_t n )
{
long long int sum = 0;
const int *q = p;
while ( q < p + n )
{
sum += *q++;
}
return sum;
}
The program output is
Array length 2
Sum of array is 2147483648
pin each iteration of the loop, making the result ofp + na moving target.