A little problem in handling 2-D arrays with class
class linklist4x4
{
private:
struct node4x4
{
开发者_如何学运维 double data[4][4];
node4x4 *link;
}*p;
public:
linklist4x4();
void append( double* num );
void add_as_first( double* num );
void addafter( int c, double* num );
//void del( double* num );
void display();
int count();
double* getdata(int c);
~linklist4x4();
};
The above is my class declaration.
Now below is a function declaration.
void linklist4x4::append(double* num)
{
node4x4 *q,*t;
if( p == NULL )
{
p = new node4x4;
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
p->data[i][j]=num[i][j];//error line
p->link = NULL;
}
else
{
q = p;
while( q->link != NULL )
q = q->link;
t = new node4x4;
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
t->data[i][j]=num[i][j];//error line
t->link = NULL;
q->link = t;
}
}
When i try to compile, it gives me an error saying that "error C2109: subscript requires array or pointer type" at the marked commented lines as shown.
Can anyone please help?
The num
passed in is a single double
pointer, but you are trying to index it with two subscripts. If you are really passing in a 4x4 double
array, change the function signature to indicate that it is such.
"num" has a single indirection so you can't dereference it twice. Declare is as
double (*num)[4]
if you want it to accept a 2D matrix so that you can apply [] to it twice.
You have defined the method append to take a 1-D array of type double. But in the function you are making use of it as a 2-D array.
The data in each of your link list node is a 2-D array of double.
So your all your member functions should accept a 2-D array of double as argument.
Change:
void append( double* num );
void add_as_first( double* num );
void addafter( int c, double* num );
to
void append( double num[][4] );
void add_as_first( double num[][4] );
void addafter( int c, double num[][4] );
You're indexing num
as if it were a 2D array or double pointer, while it is only one level deep.
double* num
num[i][j]
You can also use num[i*4+j] for accessing the data you require.
精彩评论