Reputation: 625
I have got a small problem with 1D array in c++. I have got a function line this:
void func(int (&array)[???])
{
// some math here;
"for" loop {
array[i] = something;
}
}
I call the functions somewhere in the code, and before I made math I'm not able to know dimension of the array. The array goes to the function as a reference!, because I need it in the main() function. How I can allocate array like this?, so array with ?? dimension goes to the function as reference then I have to put the dimension and write to it some values.
Upvotes: 5
Views: 2266
Reputation: 53339
If the array you pass to func
is a stack array, and not a pointer, you can retain its size by using a function template:
template <class T, size_t N>
void func(T(&array)[N])
{
size_t array_length = N; // or just use N directly
}
int main()
{
int array[4];
func(array);
}
That said, as others have already pointed out, std::vector
is probably the best solution here.
Upvotes: 5
Reputation: 2281
What you have to realize, is that arrays are pointers. A definition like int array[5]
will allocate space for 5 integers on the stack and array
will be the address of the first value. Thus, to access the first value in the array, you can write
array[0]
or *array
(which is the same as *(array + 0)
)
In the same way to retrieve the address of the third element, you can write
&array[2]
or array + 2
Since arrays are pointers, you don't have to worry about the runtime size of your array if you would like to pass it to a function, simply pass it as a pointer:
void func(int *array)
{
int size;
//compute size of the array
for (int i = 0; i < size; ++i)
{
//do whatever you want with array[i]
}
}
Upvotes: 0
Reputation: 31445
As well as vector which has been suggested you could possibly use valarray which is also part of STL and is intended specificially to handle mathematical collections.
Upvotes: 0
Reputation: 92924
Other have mentioned that you should use std::vector
in C++ and they are right.
But you can make your code work by making func
a function template.
template <typename T, size_t N>
void func(T (&array)[N])
{
// some math here;
"for" loop {
array[i] = something;
}
}
Upvotes: 10
Reputation: 363817
Use a pointer, not a reference:
void func(int *a, int N);
Or, easier, use a vector:
void func(std::vector<int> &a);
Vectors can be allocated by simply saying
std::vector<int> a(10);
The number of elements can be retrieved using a.size()
.
Upvotes: 8
Reputation: 799370
Since you're using C++, why not use a std::vector<>
instead?
Upvotes: 14