jimmu
jimmu

Reputation: 1056

Issue with allocating memory for pointers

I was asking similar question earlier. The answers I got pinpointed my mistake to not having set aside a memory for the pointer. The following piece of code still complains error: cannot convert ‘void*’ to ‘double’ in assignment. Does it mean that all elements in array are set aside as NULL?

#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>

using namespace std;
int N = 2;

int main(int argc, char *argv[])
{
double *p[N];

for(int i = 0; i<N; ++i){
    *p[i]=malloc(sizeof(double));   
}   

    *p[0] = 1.0;
    *p[1] = 2.0;
    cout << p[0] << " " << p[1] <<endl; 
    *p[0] = 5.0;
    *p[1] = 6.0;
    cout << p[0] << " " << p[1] <<endl;     
    return 0;

}

I need an array to solve a problem that I have. The array needs to be in global memory (in CUDA), which needs to be a pointer that GPUs can read/write from/to.

Upvotes: 1

Views: 53

Answers (3)

Deduplicator
Deduplicator

Reputation: 45704

*p[i]=malloc(sizeof(double));

One dereference too many, and you are running afool of C++'s stricter type checking. Use:

p[i]=(double*)malloc(sizeof**p);

Or even better C++-style:

p[i] = new double*;

Not freeing the allocated memory is acceptable only because you immediately exit the program. Better not get in the habit though. Always use the complementary deallocator, e.g.: free() for malloc(), delete for new and delete [] for new [].

Anyway, why use pointers there at all? Also, idiomatic C++ puts nearly all raw arrays into std::vector and other containers.

Upvotes: 1

CppChris
CppChris

Reputation: 1261

You might wanna do this:

double* p = new double[2];

p[0] = 1.0;
p[1] = 2.0;
p[0] = 5.0;
p[1] = 6.0;

Avoid malloc and generally be careful about allocating memory on the heap (as already indicated, you might read more about the C++ memory management).

Cheers!

Upvotes: 1

Martin James
Martin James

Reputation: 24907

p[i]=malloc(sizeof(double));

..get rid of the '*' that is dereferencing a double type and trying to assign malloc() result to it.

Upvotes: 2

Related Questions