Trying to return a pointer of type double to a function

double *Row :: getData()
{
double *newRow = new double[size];

for(int i =0; i<size; i++)
{
newRow[i] = dArray[i];
}

return *newRow;
}


//Does not work for some reason...
return *newRow;

This says "return the object that the pointer named newRow is pointing at". So that's a double. You're trying to return a double.

But this:
double *Row :: getData()
indicates that the returned object will be a pointer-to-a-double. A double is not the same as a pointer-to-a-double. If you want to return the pointer, return the pointer.
The real problem is you're passing an array back, but the size isn't known. It might be better to pass back a standard container. That way, you know how large it is, and don't have to deal with memory management.

Your correct code is:
1
2
3
4
5
6
7
8
9
10
11
double* Row::getData()
{
    double *newRow = new double[size];

    for (int i = 0; i < size; ++i)
    {
        newRow[i] = dArray[i];
    }

    return newRow;
}


An alternative implementation using an standard container:
1
2
3
4
5
6
7
8
9
10
11
std::vector<double> Row::getData()
{
    std::vector<double> newRow(size);

    for (int i = 0; i < size; ++i)
    {
        newRow[i] = dArray[i];
    }

    return newRow;
}


EDIT:
Further more, if dArray was held as a container to begin with, you could just do:
1
2
3
4
std::vector<double> Row::getData()
{
    return dArray;
}
Last edited on
If you are goint to return a pointer then return the pointer not the object referenced by this pointer

return newRow;
Topic archived. No new replies allowed.