passing array or arrays.

X

xontrn

I get the error:

"error C2664: 'C<T>::C(T **,int,int)' : cannot convert parameter 1
from 'float [2][3]' to 'float **'"

An array of array does not get resolved to a pointer-to-pointer?

#include <iostream>
using namespace std;

template<typename T>
class C
{
public:
C(T** d, int m, int n)
{
mData = new T*[m];
for(int i = 0; i < m; ++i)
mData = new T[n];

for(int i = 0; i < r; ++i)
for(int j = 0; j < c; ++j)
mData[j] = d[j];

r = m;
c = n;
}

~C()
{
for(int i = 0; i < r; ++i)
delete[] mData;

delete[] mData;
}

T& operator()(int i, int j)
{
return mData[j];
}

void print()
{
for(int i = 0; i < r; ++i)
{
for(int j = 0; j < c; ++j)
{
cout << data[j] << "\t";
}
cout << endl;
}
}

private:
T** data;
int r;
int c;
};

int main()
{
float m[2][3];
m[0][0] = 1.0f;
m[0][1] = 2.0f;
m[0][2] = 3.0f;
m[1][0] = 4.0f;
m[1][1] = 5.0f;
m[1][2] = 6.0f;
m[2][0] = 7.0f;
m[2][1] = 8.0f;
m[2][2] = 9.0f;

C<float> T(m, 2, 3);

T.print();
}
 
A

Alf P. Steinbach

* (e-mail address removed):
I get the error:

"error C2664: 'C<T>::C(T **,int,int)' : cannot convert parameter 1
from 'float [2][3]' to 'float **'"

An array of array does not get resolved to a pointer-to-pointer?

No.

A pointer-to-pointer can be a pointer to the first element of an array
of pointers to arrays. That's known as a jagged array. But the first
element of an array of arrays isn't a pointer, so a pointer to that
element isn't a pointer to a pointer.

By the way, use std::vector or e.g. a matrix class from Boost, rather
than fiddling with raw pointers and new and delete. As it is your code
is very unsafe, e.g. allowing but not supporting copying of C instances.
You avoid those kinds of errors by using standard components instead
of trying to create your own in terms of low-level operations.
 
J

James Kanze

I get the error:
"error C2664: 'C<T>::C(T **,int,int)' : cannot convert parameter 1
from 'float [2][3]' to 'float **'"
An array of array does not get resolved to a pointer-to-pointer?

No. Why should it? An array is converted implicitly to a
pointer, but the result of that conversion is a pointer, not an
array, so no further conversions of the sort apply.

Think about how pointers work, and what the layout of the
various types is in memory, and you'll quickly see why it
couldn't be otherwise. In particular, think about the
implications on pointer arithmetic (which also should explain
why in a pointer to an array, the dimension of the array must be
known).
 

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

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,244
Members
46,838
Latest member
KandiceChi

Latest Threads

Top