Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > alocation of 2D array

Reply
Thread Tools

alocation of 2D array

 
 
MMilla MMilla is offline
Junior Member
Join Date: Nov 2007
Posts: 1
 
      11-25-2007
hi I read from *.txt file size of my array and then I want to alocate this array. I have this part of code:


Quote:
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[i]);
free(matrix->matrix);
free(matrix);
}
then I tryed to write somethink, but I think, that I make mistake somewhere.


Quote:
// 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:

Quote:
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[i] = malloc(col*sizeof(int));
if (array[i] == NULL)
{
for(int u = 0; u < i; u++)
free(array[u]);
free(array);
mistake();
break;
}
}
}

//dealocation
void freeMatrix(int)
{
for (int i=0; i<row; i++)
{
free(array[i]);
}
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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
const and array of array (of array ...) Mara Guida C Programming 3 09-03-2009 07:54 AM
length of an array in a struct in an array of structs in a struct in an array of structs Tuan Bui Perl Misc 14 07-29-2005 02:39 PM
Length of Array of Array of Array Tom Perl Misc 3 12-20-2004 05:23 PM
Problem with vector<double> alocation Ivan Paganini C++ 3 10-04-2003 06:30 PM
hashed array in array need the keys... and length Daniel Perl 1 08-14-2003 06:49 PM



Advertisments