allocation of memory in 2d array

reuby_tuesday's Avatar
Light Poster
Ello all

I am currently attempting to write a program that dynamically allocates memeory according to what is in a text file.

The text file contains rows of numbers with the first row describing the size of the matrix
eg
2 3
1 2 3
2 1 3
4 5 5


after much hair pulling and fustration I am sure that it is in the memory allocation/deallocation that I am having difficulties with.

I have attached my code for these two functions which are part of a larger program. The first function opens the file and calls the memory allocation function
the next function then populates the 2d array
the next function then calcculates the required calculations on the array
the next function the displays the results
the next functuion then frees the memory

Code:
/*--------------------------------------------------------*
 * Function to free the memory*/

int FreeArray2d(int rowSize, int colSize)

{
    int **array2d;

    /*free the memory row space */
    for (int index=0; index <rowSize; index++)
        {
            free (array2d[index]);
            array2d[index] = NULL;
	}

    /*free the memory column space */
    for (int index=0; index <colSize; index++)
	{
	    free (array2d[index]);
	    array2d[index] = NULL;
	}

    /*free allocated memory*/
    free (array2d);
    array2d = NULL;

    return 0;
}
/*--------------------------------------------------------*/
/*Function to allocte memory*/

int AllocateMemory(int **array2d, int rowSize, int colSize)
{ 

    {    /*Allocate the memory for the rows of the array*/
	 /*Used malloc, as calloc wouldn't work in the same way*/
         array2d = malloc (rowSize *  sizeof(int *));
	
        /*Check that memory was allocated*/
        if (rowSize !=0 && array2d != NULL)
            {
                for (int index = 0; index < rowSize; index++)
	            {
		        array2d[index] = malloc (colSize *  sizeof(int));
		    }
	    }

        else
            {
	        fprintf(stderr, "Cannot allocate memory of size %d by %d.\n", rowSize, colSize);
            }

        return  **array2d;
	 
    }
}
Can someone have a look at the two functions above. I know that i should be using calloc instead of malloc cause it zeros the memory first.
Salem's Avatar, Join Date: Nov 2007
Ambitious contributor
Here are two different methods of allocating and freeing a dynamically allocated 2D array.
Code:
#include <stdio.h>
#include <stdlib.h>

int **make2D ( size_t rows, size_t cols ) {
    size_t  r;
    int   **result = malloc( rows * sizeof *result );
    for ( r = 0 ; r < rows ; r++ ) {
        result[r] = malloc( cols * sizeof *result[r] );
    }
    return result;
}
void free2D ( int **arr, size_t rows ) {
    size_t  r;
    for ( r = 0 ; r < rows ; r++ ) {
        free( arr[r] );
    }
    free( arr );
}

int **makeAnother2D ( size_t rows, size_t cols ) {
    size_t  r;
    int    *rp;
    int   **result = malloc( rows * sizeof *result );
    result[0] = malloc( rows * cols * sizeof *result[0] );
    for ( r = 0, rp = result[0] ; r < rows ; r++, rp += cols ) {
        result[r] = rp;
    }
    return result;
}
void freeAnother2D ( int **arr ) {
    free( arr[0] );
    free( arr );
}

int main ( ) {
    int **one = make2D( 10, 64 );
    int **two = makeAnother2D ( 10, 64 );
    int r;

    printf( "Number of bytes per row = %ld\n", 64 * sizeof(int) );
    printf( "Start of each row of one\n" );
    for ( r = 0 ; r < 10 ; r++ ) {
        printf( "%p\n", (void*)one[r] );
    }
    printf( "Start of each row of two (these are contiguous addresses)\n" );
    for ( r = 0 ; r < 10 ; r++ ) {
        printf( "%p\n", (void*)two[r] );
    }

    free2D( one, 10 );
    freeAnother2D( two );

    return 0;
}
Advantages of the 2nd method include:
- it takes only 2 mallocs to allocate the whole thing.
- the actual data is contiguous, as it would be for a true 2D array.
- you don't need the number of rows in order to free it at the end.
reuby_tuesday's Avatar
Light Poster
Thanks heaps for that. Ill implement that and will get back if I have any furether questions

Thanks again
reuby_tuesday's Avatar
Light Poster
Can someone explain what size_t does in this case. I have looked it up on the net and it doesent make any sense, so can you make your explaination preeschool level. thanks
reuby_tuesday's Avatar
Light Poster
perhaps i should just submit my entire program and see if somebody wants to try and debug it. I have the code compliing, but it dumps out at the memory allocation.
Salem's Avatar, Join Date: Nov 2007
Ambitious contributor
size_t is the type which sizeof() returns, that's all. In simplistic terms it is not that much different from an int.

Did you try to write the whole program before trying to run it?
reuby_tuesday's Avatar
Light Poster
No I was doing it slowly and in increments ,and got stuck on the momery allocation

I can read in the file, and the processing part is doable, but with out the memory allocation, and the transfer of data into the 2d array its nothing
Salem's Avatar, Join Date: Nov 2007
Ambitious contributor
Sorry, I've still no idea what it is you've tried and how you could possibly be going wrong.
Post some code.
reuby_tuesday's Avatar
Light Poster
Quote:
Originally Posted by Salem
Sorry, I've still no idea what it is you've tried and how you could possibly be going wrong.
Post some code.
Sorry, Im not bieng terribly helpful am I. Its easy to forget that you dont have a crystal ball.

Ill PM you...
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by reuby_tuesday
Sorry, Im not bieng terribly helpful am I. Its easy to forget that you dont have a crystal ball.

Ill PM you...
You can PM but you can also post them clearly here as well so that we all can have a look.