Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

passing a general 2D array

Status
Not open for further replies.

rana

Technical User
Jul 5, 2000
20
0
0
US
Hi, I'm trying to create a structure that will make it easier to pass general 2D arrays. I've created a struct:

struct matrix{
int rows;
int cols;
int **Data;
};

MATRIX construct_Matrix (int rows, int cols){
int i;
MATRIX A;
int *Data[rows];
int x[cols];
A.rows = rows;
A.cols = cols;
A.Data = Data;

for(i=0; i<rows; i++){
A.Data[0] = x;
}
return A;
}

So basically I am making an pointer in my struct that points to an array of pointers. Each pointer in the array points to an array of data so that the whole thing looks like a matrix.

Am I just setting all the pointers of the array of pointers to one array? If so, how can I make the pointers point to different arrays.
 
There's some problems with your code, I expect they are
errors of omission.

Here's an(untested)example:

Code:
typedef struct matrix {
int row;
int col;
int **parr;
} MATRIX;


MATRIX *newMatrix(int rcnt, int ccnt) {
int y = 0;
MATRIX *new = malloc(sizeof(MATRIX));

          if (new) {
              new->row = rcnt;
              new->col = ccnt;
              new->parr = malloc(rcnt * sizeof(int *));
              while (y < rcnt) {
                    new->parr[y] = malloc(ccnt * sizeof(int));
                    y++;
              }
           return new;
          }
return NULL;
}
 
oops..missed an asterisk for the initial poiter/array
assignment in newMatrix().
Should be:
int **new = malloc(rcnt * sizeof(int *));
etc..

 
> A.Data = Data;
You can't do this - you're pointing at local variables - which will go out of scope when the function exits (and will no longer exist)

Code:
A.Data = malloc( rows * sizeof(int*) );
for ( i = 0 ; i < rows ; i++ ) 
    A.Data[i] = malloc( cols * sizeof(int) );
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top