c++ dynamic size of the array

纵然是瞬间 提交于 2019-12-08 16:22:27

问题


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.


回答1:


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




回答2:


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




回答3:


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;
    }
}



回答4:


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.




回答5:


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.




回答6:


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]
    }
}



来源:https://stackoverflow.com/questions/4076664/c-dynamic-size-of-the-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!