tags:

views:

88

answers:

2

I'm trying to write a glue function between two data types and I can't seem to get the compiler to be happy. On one side, I have a pointer to a chunk of data that is logically a n x 2 array, but is declared as:

double* pData=new double[2*n];

On the other side, I have a c function that is declared as

void Function(double data[][2], int n);

If I remember my c syntax, the data[][2] is really just a pointer to a contiguous chunk of memory, but the compiler knows the size of the second dimension is 2. So I'd like to take pData and pass it into Function(), without a memcpy. I just can't seem to write the cast. I thought something like

Function((double [][2])pData,n)

would work, but the compiler (MSVC 8) doesn't like that. Can anyone let me know the proper way to write the cast to get the compiler to be happy.

+2  A: 
void Function(double data[][2], int n);
double* pData = new double[2*n];
Function((double (*)[2])pData, n);

Function parameters of the form T[] are identical to T* (not even T* const that some people expect). This is a special case for parameter types in both C and C++. So your double[][2] follows this rule, with T being double[2]. Typedefs help illustrate this:

typedef double T[2];
void Function(T data[], int n);
// identical to:
void Function(double data[][2], int n);
// also identical to:
void Function(double (*data)[2], int n);

So you write T* when T is double[2] as double (*)[2].


You could also do this:

void Function(double data[][2], int n);
double (*pData)[2] = new double[n][2];
Function(pData, n);

Which requires no cast because pData is already the correct type. Or with typedefs:

typedef double T[2];
T* pData = new T[n];
Roger Pate
+1  A: 

Just to spell it out, Andrew's answer

Function(&pData, n) 

doesn't work, you get:

error C2664: 'Function' : cannot convert parameter 1 from 'double **' to 'double [][2]'

Roger Pate's compiles, the syntax without typedefs is this:

Function( (double (*)[2]) &pData, n);
egrunin