Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sum of array using pointer arithmetic in C
In C programming, we can calculate the sum of array elements using pointer arithmetic. This approach uses pointers to traverse the array and access elements without using array indexing notation.
Pointer arithmetic allows us to navigate through memory addresses. When we use *(a + i), it accesses the element at position i from the base address a. This is equivalent to a[i] but demonstrates direct memory manipulation.
Syntax
int sum = sum + *(pointer + index);
Example
Here's a complete program that calculates the sum of array elements using pointer arithmetic −
#include <stdio.h>
void calculateSum(int *a, int len) {
int i, sum = 0;
for (i = 0; i < len; i++)
sum = sum + *(a + i);
printf("Sum of array is = %d
", sum);
}
int main() {
int arr[] = {1, 2, 4, 6, 7, -5, -3};
calculateSum(arr, 7);
return 0;
}
Sum of array is = 12
How It Works
- The function
calculateSumreceives a pointer to the first element of the array -
*(a + i)uses pointer arithmetic to access the element at indexi - The expression
a + icalculates the memory address of thei-thelement - The
*operator dereferences this address to get the actual value
Alternative Approach
We can also use pointer increment to traverse the array −
#include <stdio.h>
void calculateSumIncrement(int *ptr, int len) {
int sum = 0;
int *end = ptr + len;
while (ptr < end) {
sum += *ptr;
ptr++;
}
printf("Sum using pointer increment = %d
", sum);
}
int main() {
int arr[] = {1, 2, 4, 6, 7, -5, -3};
calculateSumIncrement(arr, 7);
return 0;
}
Sum using pointer increment = 12
Key Points
- Pointer arithmetic
*(a + i)is equivalent to array notationa[i] - When passing arrays to functions, they decay to pointers automatically
- Incrementing a pointer moves it to the next element of the same data type
Conclusion
Using pointer arithmetic to sum array elements demonstrates low−level memory access in C. This technique is fundamental for understanding how arrays and pointers work together in memory management.
