Summary: Passing Arrays as Parameters in C

In C, when passing arrays as parameters, you typically pass a pointer to the array along with an integer specifying the number of elements in the array. This is necessary because there is no built-in way to determine the size of an array in C. The function definitions using a pointer and an array are functionally equivalent:

int myFunction(int *myArray, int size) {
  // function code...
}

int myFunction(int myArray[], int size) {
  // function code...
}

Both approaches allow for indexing the array and performing pointer arithmetic. Passing arrays in this manner ensures that the function can handle arrays of various sizes without hardcoding the size.

Key Points

Comparison with JavaScript

Feature C JavaScript
Passing Arrays Pass a pointer and size explicitly Pass arrays directly without size
Determining Size No built-in way; must pass size explicitly array.length property
Array Access Indexing and pointer arithmetic Indexing with array methods
Function Syntax int myFunction(int *arr, int size) function myFunction(arr)
Dynamic Size Handling Must manually manage size parameter Arrays are dynamic; size managed automatically

Example Code

C 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[3] = {1, 2, 3};
    printArray(myArray, 3);
    return 0;
}

JavaScript Example

function printArray(arr) {
    for (let i = 0; i < arr.length; i++) {
        console.log(arr[i]);
    }
}

let myArray = [1, 2, 3];
printArray(myArray);

Detailed Comparison

  1. Passing Arrays:
  2. Determining Size:
  3. Array Access and Manipulation: