ในโปรแกรมนี้ ต้องการหาผลรวมของ array elements ด้วย pointer arithmetic
ใช้ * แทนค่าที่เก็บอยู่ที่ memory address ที่ address นั้นเก็บในตัวแปร ดังนั้น “int *ptr” หมายถึง ptr เป็นตัวแปรที่มี address และ content ของ address เป็น integer
*p หมายถึง pointer variable ใช้ร่วมกับ sum() หาผลรวม array elements
ตัวอย่างโค้ด
#include <stdio.h> void s(int* a, int len) { int i, s_of_arr = 0; for (i = 0; i < len; i++) s_of_arr = s_of_arr + *(a + i); printf( "sum of array is = %d" ,s_of_arr); } int main() { int arr[] = { 1,2,4,6,7,-5,-3 }; s(arr, 7); return 0; }ผลลัพธ์
Sum of array = 12
Algorithm
Begin Initialize array to hold the variables. Call function s to get the sum of the variables. Print the sum. End.