delete[] operator

closed account (G1vDizwU)
Hi,
Please have a look at the snip-code below:

1
2
3
4
5
6
7
8
9
10
11
double* f1();
vector<double>* f2();

void fct() 
{
  double* f1_data = f1();
  vector<double>* f2_data = f2();
  // Process
  delete[] f1_data;
  delete f2_data;
}


I think the last two lines should be this way:
1
2
 delete f1_data;
 delete[] f2_data;


Do you agree?
Last edited on
Maybe correct.
The original code may be correct as it is. Judging from the context, f1() is returning a pointer to an array of doubles. Arrays returned by new[] should be freed by delete[]. f2() appears to be returning a pointer to a single vector, which may contain many doubles. A single vector, regardless of how many elements it contains, should be deleted with delete if it was allocated by new.

Your suggestion would only be correct if f1() returns a pointer to a single double and f2() returns a pointer to an array of vectors of doubles, which I think is less likely.
Last edited on
closed account (G1vDizwU)
Thank you helios,

Would you please complete the f1() and f2() functions' bodies. That way the issue will be solved well. :)
Last edited on
For example,
1
2
3
4
5
6
7
8
9
10
11
12
13
double *f1(){
    double *ret = new double[10];
    for (int i = 0; i < 10; i++)
        ret[i] = M_PI * i;
    return ret;
}

std::vector<double> *f2(){
    std::vector<double> *ret = new std::vector<double>(10);
    for (int i = 0; i < 10; i++)
        (*ret)[i] = M_PI * i;
    return ret;
}
closed account (G1vDizwU)
Thanks.

What if the highest value of f2 is in the third element ([3]) and we have a double* f_high and want to save that third element into that f_high? what code would we use for that please?
Topic archived. No new replies allowed.