top of page

Accessing Array inside functions

  • Writer: Siddharth Sharma
    Siddharth Sharma
  • Nov 13, 2024
  • 4 min read

when you pass an array to a function, what actually gets passed is a pointer to the first element of the array. This allows the function to access and manipulate the elements of the array directly.


Basic Syntax for Accessing Arrays in Functions

Example Function Declaration

To declare a function that accepts an array, you can use either of the following methods:


void functionName(int arr[], int size);      // Using array notation
void functionName(int *arr, int size);       // Using pointer notation

Both declarations are equivalent. int arr[] and int *arr both indicate that the function receives a pointer to an integer (the first element of the array).


Example: Passing an Array to a Function

Here's a simple example demonstrating how an array can be passed to a function and accessed within that function.


#include <stdio.h>

void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);  // Access each element of the array
    }
    printf("\n");
}

int main() {
    int numbers[] = {1, 2, 3, 4, 5};  // Define an array
    int size = sizeof(numbers) / sizeof(numbers[0]);  // Calculate array size

    printArray(numbers, size);  // Pass the array and its size to the function

    return 0;
}

Explanation:


  • printArray(int arr[], int size): This function takes an integer array and its size as parameters.

  • arr[i]: Inside the function, the array elements are accessed using arr[i].

  • main(): The numbers array is passed to printArray along with its size.


Output:

1 2 3 4 5

Modifying Array Elements Inside a Function

Since arrays are passed by reference (through a pointer), modifying elements of the array within the function affects the original array.


#include <stdio.h>

void doubleArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        arr[i] *= 2;  // Modify each element by doubling it
    }
}

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int size = sizeof(numbers) / sizeof(numbers[0]);

    doubleArray(numbers, size);  // Pass the array to the function

    // Print the modified array
    for (int i = 0; i < size; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    return 0;
}

Explanation:

  • doubleArray doubles each element in the array.

  • Since arr is a pointer to the original array, modifications made to arr[i] reflect in numbers.


Output:

2 4 6 8 10

Passing a 2D Array to a Function

When working with multidimensional arrays, passing them to functions requires specifying the size of each dimension (except the first). This is necessary because C needs to know the layout of the memory to access array elements correctly.


Example: Passing a 2D Array

#include <stdio.h>

void print2DArray(int arr[][3], int rows) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
}

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

    print2DArray(matrix, 2);  // Pass the 2D array to the function

    return 0;
}

Explanation:


  • void print2DArray(int arr[][3], int rows): The function takes a 2D array arr with a known column size of 3, and rows specifying the number of rows.

  • matrix[2][3]: In main(), a 2x3 matrix is passed to print2DArray.


Output:

1 2 3
4 5 6

Alternative: Using a Pointer for 2D Arrays

Instead of hardcoding the column size, you can dynamically allocate a 2D array and pass it to a function as a pointer. This method requires more memory management.


Example with Dynamic Allocation

#include <stdio.h>
#include <stdlib.h>

void printDynamic2DArray(int **arr, int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int rows = 2, cols = 3;

    // Allocate memory for a 2D array dynamically
    int **matrix = (int **)malloc(rows * sizeof(int *));
    for (int i = 0; i < rows; i++) {
        matrix[i] = (int *)malloc(cols * sizeof(int));
    }

    // Initialize the array
    int count = 1;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matrix[i][j] = count++;
        }
    }

    printDynamic2DArray(matrix, rows, cols);

    // Free allocated memory
    for (int i = 0; i < rows; i++) {
        free(matrix[i]);
    }
    free(matrix);

    return 0;
}

Explanation:

  • printDynamic2DArray(int arr, int rows, int cols): A function that accepts a dynamically allocated 2D array as a double pointer (int arr), with rows and cols specifying the array’s dimensions.

  • Dynamic memory allocation is used in main() to allocate space for a 2D array.

  • After using the array, free() is called for each row and then for the main array pointer to avoid memory leaks.


Summary


  • 1D Arrays: Can be passed as int arr[] or int *arr. The function receives a pointer to the first element.

  • 2D Arrays with Fixed Column Size: Pass with the number of columns fixed in the parameter list (e.g., int arr[][3]).

  • Dynamically Allocated 2D Arrays: Pass as a double pointer (e.g., int **arr) when rows and columns can vary, using malloc for memory allocation.

 
 
 

Comments


bottom of page