Passing Arrays as Function Arguments in C: A Complete Beginner’s Guide

1. Introduction

Why Pass Arrays as Function Arguments in C

When programming in C, there are many situations where you need to use an array in another function. For example, operations such as batch processing of datasets or searching and sorting large amounts of data become more efficient and reusable when handled through functions that accept arrays as arguments.

Passing arrays as arguments allows for better code modularity by separating specific functionalities into individual functions. This not only makes it easier to test and debug each function independently, but also improves efficiency when multiple developers work in parallel.

This article explains in an easy-to-understand way for beginners how to pass arrays as arguments in C, along with key points to watch out for. From one-dimensional to multi-dimensional arrays, we’ll provide practical knowledge with concrete code examples.

Target Audience

This article is aimed at readers ranging from beginners who have just started learning C to intermediate users who have mastered the basics. Through this article, you will gain not only foundational knowledge of arrays and functions but also insights into memory management and pointers, enabling you to build programs more efficiently.

2. Basics of Arrays and Pointers

The Relationship Between Array Names and Pointers

In C, an array represents a contiguous block of memory, but its name has a special role—it points to the first address of the array. For example, when you declare int array[5];, the name array points to the first address of the array (&array[0]). This means you can pass an array to a function simply by using its name, and the starting address of the entire array will be passed.

Understanding this relationship is crucial because array names and pointers are closely tied in C, and this knowledge is essential when learning pointer arithmetic.

Differences Between Array Names and Pointers

While arrays and pointers share similarities, they also have important differences. For example, arrays have a fixed size, whereas pointers can be reassigned to point to different memory locations and can vary in what they reference. Additionally, arrays are stored contiguously in memory, but pointers are not necessarily pointing to contiguous memory blocks.

The following code example makes the relationship between arrays and pointers clearer:

#include <stdio.h>

void printArray(int *arr, int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
}

int main() {
    int array[5] = {1, 2, 3, 4, 5};
    printArray(array, 5);  // Pass the starting address of the array
    return 0;
}

In this code, the printArray function receives the starting address of the array and outputs each element in sequence.

年収訴求

3. How to Pass a One-Dimensional Array as a Function Argument

Basic Steps to Pass the Starting Address

In C, you can pass the starting address of an array to a function so that the function can operate on its elements. Instead of copying the entire array, only the address is passed, making it efficient and memory-friendly.

#include <stdio.h>

void modifyArray(int *arr, int size) {
    for (int i = 0; i < size; i++) {
        arr[i] *= 2;  // Double each element
    }
}

int main() {
    int array[5] = {1, 2, 3, 4, 5};
    modifyArray(array, 5);
    for (int i = 0; i < 5; i++) {
        printf("%d ", array[i]);
    }
    return 0;
}

Here, the modifyArray function doubles each element in the array. Because array’s starting address is passed, its elements can be modified inside the function.

Passing the Array Size

When passing an array to a function, you must also pass its size. C has no built-in way to determine the array length within a function, so you must specify it manually. In the above example, the size argument is used inside modifyArray to control the loop.

4. How to Pass a Multi-Dimensional Array as a Function Argument

Points to Note When Passing a 2D Array

When passing a multi-dimensional array to a function in C, you can omit the number of rows but must specify the number of columns. This ensures that the function can correctly access the array’s elements.

#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 array[2][3] = {{1, 2, 3}, {4, 5, 6}};
    print2DArray(array, 2);
    return 0;
}

Here, the column count 3 is specified in the function parameter so it can access each element correctly.

Using Variable Length Arrays (C99 and Later)

Since C99, variable length arrays (VLAs) allow you to flexibly specify array sizes in function parameters.

#include <stdio.h>

void printFlexibleArray(int rows, int cols, int arr[rows][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 array[2][3] = {{1, 2, 3}, {4, 5, 6}};
    printFlexibleArray(2, 3, array);
    return 0;
}

Using VLAs allows both row and column sizes to be specified dynamically, making multi-dimensional arrays easier to handle in functions.

5. Key Considerations When Passing Arrays

Importance of Size Management

Passing incorrect sizes can lead to memory waste or buffer overflows. Always ensure loop limits respect the array’s actual size.

Dynamic Arrays and Memory Management

When dynamically allocating arrays, use malloc and free to manage heap memory. Always free allocated memory to prevent leaks.

Side Effects from Modifying Arrays in Functions

Since arrays are passed by reference (via pointer), changes in the function affect the original array. If this is not desired, work on a copy.

6. Frequently Asked Questions (FAQ)

How Do I Get the Array Size?

C cannot determine an array’s size inside a function, so pass it explicitly, e.g., void myFunction(int *arr, int size). You can calculate the size in the caller with sizeof(array) / sizeof(array[0]):

#include <stdio.h>

void printArray(int *arr, int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
}

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

Working with Dynamic Arrays

Dynamic arrays are useful when sizes are unknown or to optimize memory use. Allocate with malloc or calloc and free afterward:

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

void fillArray(int *arr, int size) {
    for (int i = 0; i < size; i++) {
        arr[i] = i * 2;
    }
}

int main() {
    int size = 5;
    int *array = (int *)malloc(size * sizeof(int));
    if (array == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }
    fillArray(array, size);
    for (int i = 0; i < size; i++) {
        printf("%d ", array[i]);
    }
    free(array);
    return 0;
}

Which Should I Use: Arrays or Pointers?

Arrays are best for fixed-size data, while pointers are better for dynamic or variable-length data. Pointers offer more flexibility in memory operations, making them essential for advanced C programming.

7. Conclusion

Summary of Key Points

This article covered how to pass arrays as arguments in C, from one-dimensional to multi-dimensional arrays, with practical examples. Passing arrays enhances modularity and reusability, but handling them—especially dynamic or multi-dimensional arrays—requires solid understanding of pointers and memory management.

Proper size management, avoiding memory leaks, and designing functions with awareness of side effects will improve both the quality and performance of your C programs.

侍エンジニア塾