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.

calebhk98
  • 157
  • 1
  • 4
  • 15
  • 1
    Use `std::vector` or `std::array`. – jxh Dec 06 '19 at 09:27
  • This question demonstrated more research than the dup, but the dup offers fairly comprehensive answers. – jxh Dec 06 '19 at 09: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. – calebhk98 Dec 06 '19 at 09: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. – jxh Dec 06 '19 at 09:57

2 Answers2

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;
}
Blaze
  • 16,736
  • 2
  • 25
  • 44
  • That actually works thanks. Is there any documentation for that specific array type? I haven't seen that before, but it already looks useful. – calebhk98 Dec 06 '19 at 09:52
  • 1
    https://en.cppreference.com/w/cpp/container/array – jxh Dec 06 '19 at 09:53
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;
}
Math Lover
  • 148
  • 10
  • Better to use `std::unique_ptr` if you want to dynamically create the array. – jxh Dec 06 '19 at 09:37
  • 1
    Yes, I just supposed he wanted a fixed one of 5 elements as he said in the post – Math Lover Dec 06 '19 at 09:40
  • Perhaps, but your code uses `malloc`, which is dynamic. And the caller has to remember to use `free`, in a C++ program. – jxh Dec 06 '19 at 09:54
  • Right. I should improve my use of smart pointers ;) – Math Lover Dec 06 '19 at 09:56
  • https://tio.run/##jU69DoIwEN55iosOlBATFxaoPIYLEtOUai7aFkubQIzPjgcdjE7eDZd8P/d9su93VynnLRp5D50CrpW2bqqTD4J28E4JXc8ieAuXYIBl8EyAZkX0dBQODjD4riy1uKlzMPgIiqPxTVuzIqtW8cU6YIQBknhf0eFQVJDnmMUfDbbEYFQ75YMzkaiS17wYtcDf8JEcVIn9kbH2kzZ44Bw2tHRGyozOLzY9mXQJfQM – jxh Dec 06 '19 at 10:09