2

I know it is inefficient to return an array by value instead of with a pointer. However, my CS class final has a requirement that a function is to return a 5 digit 1D array as a value. As such, I can not return the array by pointer. I am also unable to have any global variables.

I have tried

float FunctionName(){
float myVar[5];
//process data
return myVar;
}

I have also tried

float[] FunctionName(){
float myVar[5];
//process data
return myVar;
}

I even tried tricking the compiler with

float FunctionName(float myVar[5]) {
     //process data
     return myVar;
 }

I have read that it is impossible, but I am guessing it is just really weird or hard to do. I think it might be possible with an enum type, but I am unsure how I would set that up.

4
  • 1
    Use std::vector or std::array. Commented Dec 6, 2019 at 9:27
  • This question demonstrated more research than the dup, but the dup offers fairly comprehensive answers. Commented Dec 6, 2019 at 9:48
  • @jxh I actually found the duplicate, but the answers all said that it was impossible, and to just use pointers. I guess the 2 are similar enough though. Commented Dec 6, 2019 at 9:56
  • 1
    You sometimes have to read beyond the accepted answer to find the right answer. In this case, look at the second most popular answer in the dup. Commented Dec 6, 2019 at 9:57

2 Answers 2

2

You can't return an array by value. However, you can do that with an std::array, which is a wrapper around an array:

#include <array>

std::array<float, 5> FunctionName() {
    std::array<float, 5> data;
    //process data
    return data;
}
Sign up to request clarification or add additional context in comments.

2 Comments

That actually works thanks. Is there any documentation for that specific array type? I haven't seen that before, but it already looks useful.
0

You can return the pointer to array in C style doing:

float* FunctionName(){
float myVar[5];

float* p = (float*) malloc(sizeof(float) * 5);
//process data

return p;
}

5 Comments

Better to use std::unique_ptr if you want to dynamically create the array.
Yes, I just supposed he wanted a fixed one of 5 elements as he said in the post
Perhaps, but your code uses malloc, which is dynamic. And the caller has to remember to use free, in a C++ program.
Right. I should improve my use of smart pointers ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.