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.
int *myArray
or int myArray[]
in function parameters is equivalent.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 |
#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;
}
function printArray(arr) {
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
}
let myArray = [1, 2, 3];
printArray(myArray);
arr.length
.length
property that provides the number of elements in the array.push
, pop
, slice
).