R
R
rsatarov2017-09-29 08:52:43
C++ / C#
rsatarov, 2017-09-29 08:52:43

How to set the size of an array through function arguments?

Let's say there is a one-dimensional array arr (like m*n elements). It is passed to the function, as well as the length and width of the two-dimensional array created from it. In the end something like this:

int * foo(int * arr, int m, int n) {
    int tempArray[m][n];
    ...
    ...
}

But it does not allow you to set the dimensions in this way ("m and n must have a constant value). How then can this be done?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
R
res2001, 2017-09-29
@res2001

Allocate memory dynamically: Only then do not forget to free it.

J
jcmvbkbc, 2017-09-29
@jcmvbkbc

But it does not allow you to set the dimensions in this way ("m and n must have a constant value). How then can this be done?

C99 allows. Use C99 already, 18 years have passed since its adoption.
A related question/answer about passing a multidimensional array directly through function arguments: How do I put an n - dimensional array into a function argument?

C
CityCat4, 2017-09-29
@CityCat4

In memory, the array will still be one-dimensional, even crack;) N-dimensionality is needed for ease of access.

F
Fat Lorrie, 2017-09-29
@Free_ze

template<size_t N, size_t M>
int* foo () {
    int tempArray[ N ][ M ];
    //...
}

// use case
foo<2, 3>();

Of course, the calculation must be in compile-time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question