Passing array as argument of a function in C++ | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 2

Passing array as argument of a function in C++

How can I pass an array as argument of a function in C++? Is it efficient?

1st Apr 2018, 7:24 PM
Dany Abreu
Dany Abreu - avatar
7 Respostas
+ 10
@Marius there is not much to clarify.. It's a very used trick, in C++ you'd better use std::vector. this trick consist of templates mixed whit size_t special features. make it simpler.. template<size_t size> // this will capture the size of your arr doSomething(int(&arr)[size])//the size obj of class size_t captures the size of the array passed.. { for(size_t i =0;i <size;++i){ ... so when you call this function.. int someData[]={1,2,3,4}; doSomething(someData);//you don't have to pass the size, size_t class do the dirty job for you!
2nd Apr 2018, 9:41 AM
AZTECCO
AZTECCO - avatar
+ 10
Try this.. template <typename T, size_t size> myFunc( T(&array)[size]){.....definition...} hope it helps :)
1st Apr 2018, 9:04 PM
AZTECCO
AZTECCO - avatar
+ 5
Here's a simple example, here we pass intArray (array of int) to the getValue function, which iterates the array to find a value (needle) and return it if found. I'm not sure what you mean by efficient, imo code efficiency lies in the coder's hand, rather than what was used. #include <iostream> int getValue(int arr[], int needle, int itemCount) { for(int i = 0; i < itemCount; ++i) { if(arr[i] == needle) return arr[i]; } return 0; } int main() { int intArray[] {1,2,3,4,5,6,7,8,9,10}; std::cout << getValue(intArray, 7, 10); return 0; } Hth, cmiiw
1st Apr 2018, 8:00 PM
Ipang
+ 4
A.) void func(int *arr) - pointer B.) void func(int arr[]) - unsized array C.) void func(int arr[10]) - sized array All three are called the same way syntactically like this: int main() { int arr[] = {1,2,3,4,5,6,7,8,9,10}; func(arr); // or func(&arr[0]); } The C++ compiler will not do out-of-bounds checking. All accomplish the same and are efficient. They all result as the parameter being passed as a pointer to the first element. Just to clarify, none of these copy the array data itself when passing it.
1st Apr 2018, 7:33 PM
Marius Heise
Marius Heise - avatar
+ 2
When you pass a pointer to an array, you should also pass the size of the array void func(int * arr, int size) {} Otherwise there's no way the function can know how big the array is - let me just say "Index out of bound". Except if your array size is a global constant, of course.
1st Apr 2018, 8:44 PM
Chris
Chris - avatar
+ 2
AZTECCO I am sure that is going to clarify everything up for Dany Abreu šŸ˜†
1st Apr 2018, 9:07 PM
Marius Heise
Marius Heise - avatar
+ 1
Hi Marius, thanks for your answer! Could you explain me the entire process? How I can receive the pointer and use it in my function?
1st Apr 2018, 7:51 PM
Dany Abreu
Dany Abreu - avatar