Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using only part of an array

Tags:

c++

arrays

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.

like image 906
PgrAm Avatar asked Dec 02 '11 22:12

PgrAm


People also ask

Is it possible to pass a portion of an array to a function?

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.

How do you free part of an array?

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() .

How do you pass part of an array in C++?

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.


1 Answers

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.

like image 187
Harper Shelby Avatar answered Oct 20 '22 16:10

Harper Shelby