I have a dynamically allocated array of float and I need to pass this array as an argument to three different functions but each function need to get a different range of the array. Is there some way I can send the array with elements 0 to 23 to one function, elements 24 to 38 to another, and elements 39 to 64 to a third function.
In some languages(like python I think) you can do something like this:
somefunction(my_array[0:23]);
somefunction(my_array[24:38]);
somefunction(my_array[39:64]);
However I am using c++ and I am not aware of any way to do this in c++.
Does anybody know how to do this?
somefunction(); is a function from an API so I can not modify the arguments it takes.
You can't pass arrays as function arguments in C. Instead, you can pass the address of the initial element and the size as separate arguments.
You can't free part of an array - you can only free() a pointer that you got from malloc() and when you do that, you'll free all of the allocation you asked for. As far as negative or non-zero-based indices, you can do whatever you want with the pointer when you get it back from malloc() .
C++ does not allow to pass an entire array as an argument to a function. However, You can pass a pointer to an array by specifying the array's name without an index.
If you write the functions to operate on a pair of forward iterators rather than an array, you could just pass it like so:
somefunction1(my_array, my_array + 24);
somefunciton2(my_array + 24, my_array + 39);
somefunction3(my_array + 39, my_array + 65);
Pointers are forward iterators, and this would allow the functions to be used over parts of vectors, queues, or other STL containers as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With