2

I'm failing at writing an OpenMP program that has to count an integral using a trapezes method.

The compiler screams at these lines:

x = calloc(n, sizeof(double));
y = calloc(n, sizeof(double));

error - a value of type "void *" cannot be assigned to an entity of type "double *"

I'm using Visual Studio 15 and yes, I enabled the OpenMP support in properties.

Here's the part of the program up to the mistake:

#define N 4
double start_time, end_time, time;
float f(float x)
{
    return(pow(x, 3));
}
void main() {
    start_time = omp_get_wtime();
    int i, n;  double *x, *y;
    double x0, xn, h, so, ans;
    x0 = 0;
    xn = 2;
    h = 0.1;
    n = (xn - x0) / h;
    if (n % 2 == 1)
    {
        n = n + 1;
    }
    x = calloc(n, sizeof(double));
    y = calloc(n, sizeof(double));

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • 1
    That's C, you're expected to use x = new double[n]; in a C++ program. If it really, really need to be zero-initialized (does it?) then you need a cast. And fret a bit that binary zeros also means 0.0. Well, don't fret too much about that, C++ compilers do tend to like IEEE 754-2008 – Hans Passant Nov 09 '20 at 22:31
  • 1
    [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) may be a better fit here. It will automatically manage the memory for you. If you find yourself needing the array inside the `vector`, you can get it with the `data` method. – user4581301 Nov 09 '20 at 22:35
  • Note: In C++ your `main` should be `int main()` (not `void`). – Adrian Mole Nov 09 '20 at 22:43

1 Answers1

4

The error message is clear and the resolution is straightforward. You need to explicitly cast the return value of calloc in C++ (unlike in C). That is, if you really need to use such "C-based" routines in C++ ...

    x = static_cast<double*>(calloc(n, sizeof(double)));
    y = static_cast<double*>(calloc(n, sizeof(double)));
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83