user1558168
user1558168

Reputation: 67

Returning an array as a pointer

I'm trying to use a separate function to read a few data values in from a file; I'm getting two errors (I haven't used c++ in a long time...):

double * FREAD(std::string fpath){
std::string line;
double * params = new double[14];


std::ifstream parameters (fpath);
if (parameters.is_open())
{
    for (int b = 0; b < 14; b++) {
        parameters >> line >> params[b];

    }
}
    parameters.close();



return params;

}

throws

error C2556: 'double *FREAD(std::string)' : overloaded function differs only by return type from 'double FREAD(std::string)'

and

error C2040: 'FREAD' : 'double *(std::string)' differs in levels of indirection from 'double (std::string)'

The second issue is thrown from the line where I call the function in main.

double * param = FREAD(parampath);

error C2440: 'initializing' : cannot convert from 'double' to 'double *'

If I don't define param as a value pointed at by a double, I get the same type mismatch error in reverse...

My understanding is that I'm supposed to return a pointer which is directed at the first value of the array my subfunction has created and use that to work with the data. But I can't seem to pull this value when I call the function in main.

Upvotes: 1

Views: 189

Answers (2)

juanchopanza
juanchopanza

Reputation: 227370

The simplest and fool-proof way to do it would be to return a container, for example

#include <array>

std::array<double,14> FREAD(const std::string& fpath)
{
  std::string line;
  std::array<double, 14> params;
  // .... fill params
  return params;
}

Concerning the overload error, you cannot overload a function by return type. It looks like the compiler is seeing these two declarations:

double * FREAD(std::string fpath);
double FREAD(std::string fpath);

Given the above suggestion, you should remove both of them anyway.

Upvotes: 6

Adam
Adam

Reputation: 17329

Your error C2556 is because you apparently have another FREAD() function that returns something else. The error is telling you that you can't overload functions based only on the return type.

Going from the messages, it appears to me that you have two functions:

  • double * FREAD(std::string fpath)
  • double FREAD(std::string fpath)

You only posted the first one.

C++ only allows you have two functions with the same name if they take different arguments (or const-ness for member functions). You should either give your functions different names, or pass in a token argument that the compiler can use to tell which one you want.

Upvotes: 1

Related Questions