Passing Arrays as Function Arguments in C

Hello there, future coding superstar! ? Today, we're going to embark on an exciting journey through the world of arrays and functions in C. As your friendly neighborhood computer science teacher, I'm here to guide you through this adventure step by step. So, grab your virtual backpack, and let's dive in!

C - Passing Arrays to Function

Understanding Arrays and Functions

Before we jump into passing arrays to functions, let's quickly refresh our memory about what arrays and functions are.

What's an Array?

Think of an array as a line of lockers in a school hallway. Each locker (element) has a number (index) and can store something inside it. In C, we use arrays to store multiple items of the same type in a single variable.

What's a Function?

A function is like a mini-program within our main program. It's a set of instructions that performs a specific task. Think of it as a recipe card in a cookbook – you can use it whenever you need to perform that particular task.

Now that we've got our basics covered, let's explore how we can combine these two concepts!

Passing Arrays as Function Arguments

In C, we can pass arrays to functions in different ways. Let's look at each method one by one.

1. Pass Array with Call by Value Method

In C, when we pass an array to a function, we're actually passing the address of the first element of the array. This means that any changes made to the array inside the function will affect the original array.

Let's look at an example:

#include <stdio.h>

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

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

    printf("Original array: ");
    printArray(myArray, size);

    return 0;
}

In this example, we're passing myArray to the printArray function. Even though it looks like we're passing the entire array, we're actually passing a pointer to the first element.

Output:

Original array: 1 2 3 4 5

2. Pass Array with Call by Reference

In C, arrays are always passed by reference. This means that when you pass an array to a function, you're actually passing a pointer to the first element of the array.

Let's see an example where we modify the array inside the function:

#include <stdio.h>

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

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

    printf("Original array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", myArray[i]);
    }
    printf("\n");

    doubleElements(myArray, size);

    printf("Modified array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", myArray[i]);
    }
    printf("\n");

    return 0;
}

In this example, the doubleElements function modifies the original array by doubling each element.

Output:

Original array: 1 2 3 4 5
Modified array: 2 4 6 8 10

3. Pass Two-Dimensional Array to Function

Now, let's level up and talk about passing 2D arrays to functions. It's like handing over a whole spreadsheet instead of just a single row!

Here's an example:

#include <stdio.h>

void print2DArray(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 myArray[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

    printf("My 2D Array:\n");
    print2DArray(3, 3, myArray);

    return 0;
}

In this example, we're passing a 2D array to the print2DArray function. Notice how we specify the dimensions in the function parameter.

Output:

My 2D Array:
1 2 3
4 5 6
7 8 9

4. Function to Compare String Lengths

Last but not least, let's look at how we can pass strings (which are essentially character arrays) to functions. We'll create a function that compares the lengths of two strings.

#include <stdio.h>
#include <string.h>

int compareStringLengths(char str1[], char str2[]) {
    int len1 = strlen(str1);
    int len2 = strlen(str2);

    if (len1 > len2) return 1;
    if (len1 < len2) return -1;
    return 0;
}

int main() {
    char string1[] = "Hello";
    char string2[] = "World!";

    int result = compareStringLengths(string1, string2);

    if (result > 0) {
        printf("%s is longer than %s\n", string1, string2);
    } else if (result < 0) {
        printf("%s is longer than %s\n", string2, string1);
    } else {
        printf("%s and %s have the same length\n", string1, string2);
    }

    return 0;
}

In this example, we're passing two strings to the compareStringLengths function, which returns 1 if the first string is longer, -1 if the second string is longer, and 0 if they're the same length.

Output:

World! is longer than Hello

Conclusion

Congratulations! You've just leveled up your C programming skills by learning how to pass arrays to functions. Remember, practice makes perfect, so don't hesitate to experiment with these concepts in your own programs.

Here's a quick reference table of the methods we've covered:

Method Description
Pass Array with Call by Value Passes the address of the first element
Pass Array with Call by Reference Always passes by reference in C
Pass 2D Array Requires specifying dimensions in function parameter
Pass Strings Can be used to manipulate or compare strings

Keep coding, keep learning, and most importantly, keep having fun! ??

Credits: Image by storyset