alocation of 2D array

Joined
Nov 25, 2007
Messages
1
Reaction score
0
hi I read from *.txt file size of my array and then I want to alocate this array. I have this part of code:


typedef struct tmatrix
{
int rows, cols;
int *matrix;
} TMatrix;

int readMatrix(FILE *f, TMatrix *matrix)
{
.
.
.
*matrix=alocateMatrix(rows,cols);
.
.
.
}


int alocateMatrix(r,c)
{
int **array = malloc(r*sizeof(int *));
for (j = 0; j < matice->r; j++)
array[j] = malloc(c*sizeof(int));
return // what would this funcion return? I tried something, but wasnot OK
}



//then I dealocated:
void freeMatrix(TMatrix *matrix)
{
int i;
for (i=0;i<matrix->rows;i++) free(matrix->matrix);
free(matrix->matrix);
free(matrix);
}


then I tryed to write somethink, but I think, that I make mistake somewhere.


// I would like to alocate as 2D array
TMatrix alocation(unsigned int row, unsigned int col)
{
TMatrix matrix;

int *mat = malloc(row * col * sizeof(int));
if (mat == NULL)
{
matrix_error();
free(mat);
}

matrix.col = col;
matrix.row = row;
matrix.matrix = mat;

return matrix;
}


void freeMatrix(TMatrix *matrix)
{
free(matrix->matrix);
}

or I tried this:

TMatrix alocation(unsigned int row, unsigned int col)
{
int**array = malloc(row*sizeof(int*));
if(array == NULL)
mistake();
for (int i = 0; i < row; i++)
{
array = malloc(col*sizeof(int));
if (array == NULL)
{
for(int u = 0; u < i; u++)
free(array);
free(array);
mistake();
break;
}
}
}

//dealocation
void freeMatrix(int)
{
for (int i=0; i<row; i++)
{
free(array);
}
free(array);
}


I am agonized, I'm trying all night and I can't make it in order to be OK. I can try write something else...
MMilla
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top