Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing around fixed-size arrays in C++?

Tags:

Basically I'd like to do something like that:

int[3] array_func()
{
    return {1,1,1};
}

int main(int argc,char * argv[])
{
    int[3] point=array_func();
}

But that doesn't seem legal in C++. I know I can use vectors, but since I know the size of the array is a constant, it seems like a loss of performance is likely to occur. I'd also like to avoid a new if I can, because allocating stuff on the stack is easier and also likely to improve performance.

What's the solution here?

like image 831
static_rtti Avatar asked Nov 18 '09 10:11

static_rtti


People also ask

Do arrays have fixed size in C?

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type.

How do you pass the size of an array to a function?

The first one would be called like func1(foo, foo + CAPACITY) : passing in a pointer to the start of the array, and a pointer to just beyond the last element. The second would be called like func2(foo, CAPACITY) : passing in a pointer to the start of the array and the array size.

What are 2 typical problems with fixed array sizes?

Because fixed arrays have memory allocated at compile time, that introduces two limitations: Fixed arrays cannot have a length based on either user input or some other value calculated at runtime. Fixed arrays have a fixed length that can not be changed.

Why do we pass size of array in C?

Passing the array size tells the function where the bounds are so you can choose not to go beyond them. This is inherited from C language, if you use std::array or std::vector you don't need to use array size as a parameter function.


2 Answers

Using C++0x, the almost finalized new C++ standard (already implemented in latest gcc and msvc IIRC), you can do it exactly as you want! Simply use std::array instead of int[3].

std::array<int, 3> array_func()
{
    return {1,1,1};
}

int main(int argc,char * argv[])
{
    std::array<int, 3> point = array_func();
}
like image 51
Didier Trosset Avatar answered Sep 22 '22 18:09

Didier Trosset


Put the array into a struct. boost::array is such a package:

boost::array<int, 3> array_func() {
  boost::array<int, 3> a = {{ 1, 1, 1 }};
  return a;
}

int main() {
  boost::array<int, 3> b = array_func();
}

Quick and dirty:

template<typename E, size_t S>
struct my_array {
  E data[S];
};

Notice how you can use aggregate initialization syntax.

like image 24
Johannes Schaub - litb Avatar answered Sep 22 '22 18:09

Johannes Schaub - litb