-2

So I want to make an executable with three functions:

This would be an example:

float vec(int opt, int t)
{
int i;
float * v = new float[t];
// Do stuff with v
return * v;
}
}

It gets arguments opt and t from main. Then main needs to get v back to use it in another function.

What is the best way to do this?

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
D1X
  • 5,025
  • 5
  • 21
  • 36

2 Answers2

2

The return type of vec should be float *, and your return statement should be return v. Dereferencing v with * just gives you the first element of the array.

I'll note that this kind of design is bad style. It relies on the caller to free the dynamically allocated array. It would be better to have the caller create an array and pass it by reference to vec, or have vec return a different container statically. @Mat suggested std::vector; that's probably a good choice.

You also have an extra } at the end of your function. Get rid of it.

user2752467
  • 864
  • 5
  • 16
0

Well, your signature says that the function returns a single float, not an array of floats. To answer your question directly...

float *vec(int t)
{
    float * v = new float[t];
    // Do stuff with v
    return v;
}

What is the best way to do this?

Well that's a different question entirely. The "best" way would be to return a std::vector<float> and avoid manual memory management altogether.

Ed S.
  • 122,712
  • 22
  • 185
  • 265