Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ dynamic size of the array

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.

like image 361
nykon Avatar asked Nov 02 '10 10:11

nykon


4 Answers

Since you're using C++, why not use a std::vector<> instead?

like image 156
Ignacio Vazquez-Abrams Avatar answered Oct 21 '22 03:10

Ignacio Vazquez-Abrams


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

like image 40
Fred Foo Avatar answered Oct 21 '22 04:10

Fred Foo


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;
    }
}
like image 10
Prasoon Saurav Avatar answered Oct 21 '22 05:10

Prasoon Saurav


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.

like image 5
Charles Salvia Avatar answered Oct 21 '22 03:10

Charles Salvia