Sometimes one pays most for the things one gets for nothing.

— Albert Einstein

C++ Array as argument

When an array is argument of function the address of first element is passed, not copy of an entire array. Thus it can be declared 3 ways in the list of parameters.

  • Array with specified size and data type
  • Array with specified data type
  • Array as a pointer

Array with specified size and data type

This way we specify exactly expected size and data-type of array.


void printArray(int arr[5]){
for(int i=0; i<5; i++){
cout << "Value of arr["<< i <<"] is " << arr[i] << ";\n";
}
}

It is allowed to pass as a parameter of this function array declared with the different size for example

int arr[10]; //array of 10 integer values

the program will compile and not throw any exception.

Array with specified data type

Or passing unsized array.
In this case we will specify only the data-type and the fact that parameter is an array.

void printArray(int arr[]){
for(int i=0; i<5; i++){
cout << "Value of arr["<< i <<"] is " << arr[i] << ";\n";
}
}

Array as a pointer

Any pointer can be indexed using [] as if it were an array.

void printArray(int *arr){
for(int i=0; i<5; i++){
cout << "Value of arr["<< i <<"] is " << arr[i] << ";\n";
}
}
int arr[2];//declaration of one dimensional array
printArray(arr);//function call

Such a code will be perfectly valid.