error C2440

A

Allen Maki

Hi everybody,

Thanks for your suppoty.

//Why I got the following error message? for the 4th line:

// error C2440: '=' : cannot convert from

//'long (*)[3]' to 'long *' Types pointed

//to are unrelated; conversion requires

// reinterpret_cast, C-style cast or

//function-style cast





#include <iostream>

using namespace std;


int main()

{

const int max = 4; //(1)

const int max2 = 3; //(2)

long *pprime; //(3)

pprime = new long[max][max2]; //(4)


return 0;

}
 
T

Tamas Demjen

Allen said:
// error C2440: '=' : cannot convert from

//'long (*)[3]' to 'long *' Types pointed

That's because the left hand side doesn't match the type of the right
hand side.

The best way to use 2D arrays is to flatten them. Allocate a 1D array of
the size columns * rows:

long * pprime = new long[columns * rows];

and calculate the linearized index on your own, like this:

pprime[row * columns + column] = 0;

You need to take care of deleting your array when it's not used anymore:

delete [] pprime;

If you absolutely need the [row][column] syntax, or if the number of
columns is different in each row, then you have to allocate an array of
pointers, and then for each row allocate an array that holds the columns:

long** matrix = new long[rows];
for(int i = 0; i < rows; ++i)
matrix = new long[columns];

matrix[row][column] = whatever;

[...]

for(int i = 0; i < rows; ++i)
delete [] matrix;
delete [] matrix;

I strongly recommend that you use std::vector if you program in C++, and
use a 1D vector instead of a 2D one.

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top