Pointers with Arrays and Functions in C Programming (Complete Guide with Examples)


This tutorial explains how pointers can be used with arrays and functions in C. It covers accessing array elements using pointers, passing arrays to functions using pointers, and practical examples to help beginners understand memory-efficient programming.

1. Pointers and Arrays

  1. The name of an array acts as a pointer to the first element.
  2. Example:

int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // points to arr[0]

printf("%d\n", *ptr); // 10
printf("%d\n", *(ptr+1)); // 20

2. Passing Arrays to Functions Using Pointers

  1. Instead of passing the whole array, we pass a pointer to the first element.
  2. This is memory-efficient and allows the function to modify the array.

Syntax


void function_name(int *arr, int size) {
// access elements using pointer
}

3. Example Program: Sum of Array Elements Using Pointer


#include <stdio.h>

// Function to calculate sum using pointer
int sumArray(int *arr, int n) {
int sum = 0;
for(int i = 0; i < n; i++)
sum += *(arr + i); // pointer arithmetic
return sum;
}

int main() {
int arr[5] = {10, 20, 30, 40, 50};
int total = sumArray(arr, 5); // pass array as pointer

printf("Sum of array elements: %d\n", total);
return 0;
}

Sample Output:


Sum of array elements: 150

4. Example Program: Modify Array Using Pointer in Function


#include <stdio.h>

// Function to double each element
void doubleArray(int *arr, int n) {
for(int i = 0; i < n; i++)
*(arr + i) *= 2;
}

int main() {
int arr[5] = {1, 2, 3, 4, 5};

doubleArray(arr, 5);

printf("Modified array: ");
for(int i = 0; i < 5; i++)
printf("%d ", arr[i]);

return 0;
}

Sample Output:


Modified array: 2 4 6 8 10

Observation: Changes inside the function affect the original array, because arrays are passed by pointer (address).

5. Key Points to Remember

  1. Array name is a pointer to the first element
  2. arr[i] is equivalent to *(arr + i)
  3. Passing arrays to functions via pointers is efficient
  4. Modifications inside the function change the original array
  5. Useful for large arrays and dynamic memory operations