0

I got a problem in my code by allocating a two-dimensional array for double values. So first the code I use:

double** matrix;
double ncolumn=2;
double nrow;

for (size_t i=0; i<nSlices; ++i) {
    const std::vector<LineSegment> &lss = slicesWithLineSegments[i];
    //I use 
    nrow = lss.size();//Returns the numbers ob Row;
    matrix = malloc(nrow*sizeof(double*));

    for (size_t j=0; j<nrow; ++j) 
    {
        matrix[j] = malloc(ncolumn * sizeof(double));
    }
}

Since I have a number of segments, and each segment has a different number of lines, I have to edit the array for each segment. That's why i use the for-loop with nSlices.

But in the two lines with the malloc commands I get a error from visual studio. Here's the error-message:

error C2440: '=' : cannot convert from 'void *' to 'double *'
error C2440: '=' : cannot convert from 'void *' to 'double *'
IntelliSense: a value of type "void *" cannot be assigned to an entity of type "double **"
IntelliSense: a value of type "void *" cannot be assigned to an entity of type "double *"

I also tried to use calloc, but I also got this error messages. I also had a look on google, and just found the code in the way I did it. But the errors still remain.

user3794592
  • 183
  • 2
  • 16
  • you have to cast `(double *) malloc( ... ) ` in c++ or to use ̀new double*` – Pierre Emmanuel Lallemant Jan 18 '16 at 12:07
  • So do I write: matrix = (double* ) malloc(nrow*sizeof(double*)); and matrix[j] = (double *) malloc(ncolumn * sizeof(double)); – user3794592 Jan 18 '16 at 12:08
  • 4
    Please! This is C++. Use `new[]` and `delete[]`, or better yet, `vector`. – Roddy Jan 18 '16 at 12:09
  • @Roddy I'm using now the new[] command and now I'm able to allocate the memory. To free the memory do I have to use the reverse path for the array. So first the delete[] command in a for-loop, than delet[] for the array? – user3794592 Jan 18 '16 at 12:22
  • @user3794592 Yes. (but `std::vector` would save you the trouble of deleting) – Roddy Jan 18 '16 at 12:44

3 Answers3

1

malloc returns a (void*) pointer, you should cast the return to (double**) and (double*)

matrix = (double**)malloc(nrow*sizeof(double*));

matrix[j] = (double*)malloc(ncolumn * sizeof(double));
davmac
  • 20,150
  • 1
  • 40
  • 68
1

The error messages plainly tell you what's going on: malloc returns void* which is neither double**, nor double*. Either cast the result:

matrix = (double**)malloc(nrow*sizeof(double*));
// ...
matrix[j] = (double*)malloc(ncolumn * sizeof(double));

or refactor to std::vector<double> (note: not std::vector<std::vector<double>> if a dense matrix is required, see this answer) which is easier and safer.

Community
  • 1
  • 1
Pixelchemist
  • 24,090
  • 7
  • 47
  • 71
0

malloc return void *. Try (double *) before malloc or use operator new

Dmitriy
  • 847
  • 17
  • 39