How to pass double[][] into a method call?
Hi I am tryin开发者_运维知识库g to init an object with a double value in the format double filter[3][3]; but i keep getting the following error.
cannot convert 'double[3][3]' to 'double' in assignment.
in my header i have this
@interface filter : NSObject
{
double **matrix;
}
@property(nonatomic)double **matrix;
-(id)initWithMatrix:(double**)filterMatrix;
inside my class i have this method.
-(id)initWithMatrix:(double**)filterMatrix
{
matrix = filterMatrix;
return self;
}
and i am trying to call it like this.
double filter[3][3] = {0,0,0,0,1,0,0,0,0};
MyMatrix *myMatrix = [[MyMatrix alloc] initWithMatrix:filter];
I now get the error.
Error: Cannot convert double[*][3] to double** in argument passing
Any help on this issue would be amazing. Thanks A
That's because double**
isn't the equivalent of double[*][*]
. In fact, double[*][*]
is an invalid type, because it leaves the stride undefined. double**
is a pointer to a pointer to a double, or to put it another way, it's a pointer to an array of doubles. You should just use double*
as your type.
Edit: To clarify, double[*][3]
is still just an array of doubles, even though it has 2 dimensions. This is still the equivalent of double*
.
A two-dimensional array is not the same thing as a pointer-to-a-pointer. You have two choices - change the filter
class to contain a 2D array, or change your initialization to use pointer-to-pointers.
In choice #1, you're could keep a copy of the array in your filter
instance, instead of just holding a pointer. You need to change the class interface:
@interface filter : NSObject
{
double matrix[3][3];
}
-(id)initWithMatrix:(double[3][3])filterMatrix;
Then your implementation of initWithMatrix:
can just do a memcpy()
or the equivalent to copy the data into your instance.
Choice #2 is a bit different. Keep your other code the way it is, but change your initialization of filter
:
double row0[3] = {0,0,0};
double row1[3] = {0,1,0};
double row2[3] = {0,0,0};
double **filter[3] = { row0, row1, row2 };
It's probably safer to malloc()
all of those arrays, since otherwise you're going to end up with references to stack variables in your filter
class, but I think you get the idea.
you are passing as a parameter a double 2d array(double[][]) when your method signature asks for a double (a primitive like 34.2). set the method declaration to
- (id)initWithMatrix:(double*) matrix;
this passes a pointer to your array (2d) to the method. edit: missed a semicolon.
精彩评论