Menu
Coddy logo textTech

Array as a Parameter

Lesson 9 of 17 in Coddy's Functions in C course.

A function can also accept an array as a parameter just like any other variable. The only difference is that an array is passed as a pointer to the function, unlike other primitive types that we pass by value.

When an array is passed to a function, the function receives a pointer to the first element of the array.

Let's take an example of how to use it:

#include <stdio.h>

// Function definition
void printArray(char *arr[]) {
    for (int i = 0; i <= 3; i++) {
        printf("%s ", arr[i]);
    }
    printf("\n");
}

int main() {
    char *a[] = {"C", "Java", "React", "Python"};

    // Calling the function
    printArray(a);

    return 0;
}

In the main function, we define a simple array:

char *a[] = {"C", "Java", "React", "Python"};

In the printArray function, we loop from 0 to 3 and print each value:

   for (int i = 0; i <= 3; i++) {
       printf("%s ", arr[i]);
   }

The output will be like this:

C Java React Python 

Note: When we deal with strings, we explicitly need to use the asterisk (*) to tell the compiler that each string (e.g., "Java") is an element of the array. Otherwise, it will take each character (e.g., 'J') as an element.

challenge icon

Challenge

Easy

Write a function called printDouble that will take an array of numbers, double each element, and print the resulting list to the screen.

For example, given the input:

2 6 8 10

The output will be:

4 12 16 20

Try it yourself

#include <stdio.h>

// Function definition



int main()
{
    // Don't Change this
    int nums[] = {10, 6, 22, 40, 1}};
   // Call the Function
    printDouble(nums);
     
    return 0;
}

All lessons in Functions in C