Dynamic Memory Allocation for Matrix(2D Array)

Peter_APIIT's Avatar, Join Date: Apr 2007
Contributor
Hello all expert C programmer especially shabbir,

i have a question which bring my emotion from happy to unhappy. My program is a use of techniques dynamic memory allocation to alocate the memory for 2D array. I have successfully allocating the memory for 2D but when i try to add two matrix, the program just display an error message which force my program terminated.

I know this situation is related to run time error. I try to debug and catch the errors. Unfortunately, my effort doesn't bring any desires results.

I hope that someone which kind enough to help me in this problem.

Below is my code:

Code:
/* Best Method to allocate memory for 2D Array because it's 
   much more flexible
*/
                
/* int ***matrixptr ->  **rowptr     ->   *rowptr[nrow]  ->   element of row
					    1st Matrix   ->   *rowptr[nrow]  ->   element of row
                                     ->   *rowptr[nrow]  ->   element of row
					                               
					->  **rowptr     ->   *rowptr[nrow]  ->   element of row
					    2nd Matrix   ->   *rowptr[nrow]  ->   element of row
                                     ->   *rowptr[nrow]  ->   element of row

                    ->  **rowptr     ->   *rowptr[nrow]  ->   element of row
                        3nd Matrix   ->   *rowptr[nrow]  ->   element of row
					                 ->   *rowptr[nrow]  ->   element of row
*/
// How do code this in C

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

/* int **rowptr -- A pointer to pointer to integer
   This can be explain through graphically.
   int **rowptr  ->   *rowptr[nrow] ->  element of row
                 ->   *rowptr[nrow] ->  element of row
				 ->   *rowptr[nrow] ->  element of row
*/
int Symmetric(int, int, int, int);
void Add(int **, int **, int, int, int, int);

void Display(int **, int , int );
//	int *nrow_ptr = NULL, *ncol_ptr = NULL;  

/*	int *nrow_ptr, *ncol_ptr;
	// Declare the nrow_ptr and ncol pointer
	nrow_ptr = &nrow;
	ncol_ptr = &ncol;
	// Initialized the nrow_ptr and ncol_ptr
*/   


int main(int argc, char *argv[])
{
	int nMatrix;
	int nrow, ncol, nrow_1, ncol_1;
	// Number of row and column
	
	int row_loop, col_loop;
	// Loop for row and column

	int **rowptr = NULL;   // -- First Matrix
	// A pointer to pointer to integer

	int **rowptr_1 = NULL; // -- Second Matrix
	int **result = NULL;  // Result of two Matrix
	int symmetric;
	/*
	   Used while loop instead of dowhile because it's recommended
	   by Bjarne Stroustrup	
	*/
// ------------------------------------------------------------
	while(1)
	{	// Must allocate at least two matrix
		printf("\nPlease Enter same dimension for two Matrix\n");
		printf("\nHow many Matrix : ");
		scanf("%d", &nMatrix);
		switch(nMatrix)
		{
		    case 1:
			{
				printf("How many Row : ");
				scanf("%d", &nrow);
				rowptr = malloc(sizeof(int) * nrow);
				if (rowptr == NULL)
				{
					perror("Dynamic Memory Allocation for row Fails");
				}	
				printf("How many Column : ");					scanf("%d", &ncol);

				for (row_loop=0;row_loop<nrow;row_loop++)
				{
					rowptr[row_loop] = malloc(sizeof(int) * ncol);
					if (rowptr[row_loop] == NULL)
					{	
						perror("Dynamic Memory Allocation for column Fails");
					}
				}

				for (row_loop=0;row_loop<nrow;row_loop++)
				{
					for (col_loop=0;col_loop<ncol;col_loop++)
					{
						printf("Enter the [%d][%d] number : ", row_loop, col_loop);
						scanf("%d", &rowptr[row_loop][col_loop]);
					}
				}
				break;
			}
// ------------------------------------------------------------
			case 2:
			{	// Enter the first matrix
				do
				{
					printf("Enter the First Matrix : \n");
					printf("How many Row : ");
					scanf("%d", &nrow);
					rowptr = malloc(sizeof(int) * nrow);
					if (rowptr == NULL)
					{
						perror("Dynamic Memory Allocation for row Fails");
					}	
					printf("How many Column : ");
					scanf("%d", &ncol);

					for (row_loop=0;row_loop<nrow;row_loop++)
					{
						rowptr[row_loop] = malloc(sizeof(int) * ncol);
						if (rowptr[row_loop] == NULL)
						{
							perror("Dynamic Memory Allocation for column Fails");
						}
					}

					for (row_loop=0;row_loop<nrow;row_loop++)
					{
						for (col_loop=0;col_loop<ncol;col_loop++)
						{
							printf("Enter the [%d][%d] number : ", row_loop, col_loop);
							scanf("%d", &rowptr[row_loop][col_loop]);
						}
					}
// -----------------------------------------------------------
					// Enter the second Matrix
					printf("Enter the Second Matrix : \n");
					printf("How many row : ");
					scanf("%d", &nrow_1);
					rowptr_1 = malloc(sizeof(int) * nrow_1);
					if (rowptr_1 == NULL)
					{
						perror("Dynamic Memory Allocation Matrix 2 for row Fails");
					}
					printf("How many Column : ");
					scanf("%d", &ncol_1);

					for (row_loop=0;row_loop<nrow_1;row_loop++)
					{
						rowptr_1[row_loop] = malloc(sizeof(int) * nrow_1);
						if(rowptr_1[row_loop] == NULL)
						{
							perror("Dynamic Memory Allocation Matrix 2 for column Fails");
						}
					}
					
					for (row_loop=0;row_loop<nrow_1;row_loop++)
					{
						for (col_loop=0;col_loop<ncol_1;col_loop++)
						{
							printf("Enter the [%d][%d] number : ", row_loop, col_loop);
							scanf("%d", &rowptr_1[row_loop][col_loop]);
						}
					}
					break;
				}while(symmetric == 0);
			}
		}
// ------------------------------------------------------------				
		// Check the Dimension of Two Matrix
		symmetric = Symmetric(nrow, ncol, nrow_1, ncol_1);
		if (symmetric == 1)
		{
			printf("The two Matrix is same dimension");
		}
		else
		{
			printf("The two Matrix is different dimension");
		}

               // Runtime Error
		Add(rowptr, rowptr_1, nrow, ncol, nrow_1, ncol_1);
		// Adding the element of matrix
		Display(result, nrow, ncol);
		// Display the result after successful allocated the memory

		free(rowptr);
		free(rowptr_1);
		free(result);
	}


	return 0;

}
// -----------------------------------------------------------
int Symmetric(int nrow, int ncol, int nrow_1, int ncol_1)
{
	int symmetric;
	if (nrow == nrow_1 && ncol == ncol_1)
	{
		symmetric = 1;
		return symmetric;
	}
	else
	{
		symmetric = 0;
		return symmetric;
	}
}
// ------------------------------------------------------------	
void Add(int **rowptr, int **rowptr_1, int nrow, 
		 int ncol, int nrow_1, int ncol_1)
{
	int **result = NULL;
	int row_loop, col_loop;
	nrow = nrow_1;
	ncol = ncol_1;

	for (row_loop = 0;row_loop < nrow; row_loop++)
	{
		for (col_loop = 0; col_loop < ncol; col_loop++)
		{
			*(*(result + row_loop) + col_loop) =  (*(*(rowptr + row_loop) + col_loop))   +  (*(*(rowptr_1 + row_loop) + col_loop));
		}
	}

}

// ------------------------------------------------------------
void Display(int **result, int nrow, int ncol)
{
	int row_loop, col_loop;
	// Loop for row and column

	for (row_loop = 0; row_loop < nrow; row_loop++)
	{
		for (col_loop = 0; col_loop < ncol; col_loop++)
		{
			printf("The value of array at [%d][%d] is %d\n", row_loop, col_loop, *(*(result + row_loop) + col_loop) );
		}
	}

}

// ------------------------------------------------------------
The error is appear after i check the dimension of the 2D array.

Thanks for your help.

Your help is greatly appreciated by me and others.
0
ahayes's Avatar, Join Date: Mar 2007
Light Poster
nrow_1 needs to be ncol_1

Code:
for (row_loop=0;row_loop<nrow_1;row_loop++)
					{
						rowptr_1[row_loop] = malloc(sizeof(int) * nrow_1); //<--error is here
						if(rowptr_1[row_loop] == NULL)
						{
							perror("Dynamic Memory Allocation Matrix 2 for column Fails");
						}
					}
You are not allocating memory for the result matrix so you need to make this modification

Code:
void Add(int **rowptr, int **rowptr_1, int nrow, 
		 int ncol, int nrow_1, int ncol_1)
{
	int **result = NULL;
	int row_loop, col_loop;
	nrow = nrow_1;
	ncol = ncol_1;
	
	result = malloc(sizeof(int*) * nrow_1);
					if (rowptr_1 == NULL)
					{
						perror("Dynamic Memory Allocation Matrix Result for row Fails");
					}

					for (row_loop=0;row_loop<nrow_1;row_loop++)
					{
						result[row_loop] = malloc(sizeof(int) * ncol_1);
						if(rowptr_1[row_loop] == NULL)
						{
							perror("Dynamic Memory Allocation Matrix Result for column Fails");
						}
					}

	for (row_loop = 0;row_loop < nrow; row_loop++)
	{
		for (col_loop = 0; col_loop < ncol; col_loop++)
		{
			*(*(result + row_loop) + col_loop) =  (*(*(rowptr + row_loop) + col_loop))   +  (*(*(rowptr_1 + row_loop) + col_loop));
		}
	}

}
also, when you are allocating for rows you need to have sizeof( (*int) * nrows) and not just sizeof((int)*nrows)
0
wrecker's Avatar, Join Date: Mar 2007
Go4Expert Member
Hey man, giving a first look to your code it looked as if you are well versed i programming, but after thoroughly going i thought either you are not clear with mem managament concepts of have just copied code.
i have made certain change that ececute code correctly.
Many Confusing comments were given...
I am still not able to figure the need of them...
Also many unnecessary inputs were asked....
and theres no ned to take symmetric matrix, any matrix with resultant matrix equal to size of largest matrix would solve the problem...
Go through changes and understand..
Also try to use code that others should feel easy to understand....


Code:
/* Best Method to allocate memory for 2D Array because it's 
   much more flexible
*/
                
/* int ***matrixptr ->  **rowptr     ->   *rowptr[nrow]  ->   element of row
					    1st Matrix   ->   *rowptr[nrow]  ->   element of row
                                     ->   *rowptr[nrow]  ->   element of row
					                               
					->  **rowptr     ->   *rowptr[nrow]  ->   element of row
					    2nd Matrix   ->   *rowptr[nrow]  ->   element of row
                                     ->   *rowptr[nrow]  ->   element of row

                    ->  **rowptr     ->   *rowptr[nrow]  ->   element of row
                        3nd Matrix   ->   *rowptr[nrow]  ->   element of row
					                 ->   *rowptr[nrow]  ->   element of row
*/
// How do code this in C

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include"conio.h"

/* int **rowptr -- A pointer to pointer to integer
   This can be explain through graphically.
   int **rowptr  ->   *rowptr[nrow] ->  element of row
                 ->   *rowptr[nrow] ->  element of row
				 ->   *rowptr[nrow] ->  element of row
*/
int Symmetric(int, int, int, int);
void Add(int **, int **, int, int, int, int);

void Display(int **, int , int );
//	int *nrow_ptr = NULL, *ncol_ptr = NULL;  

/*	int *nrow_ptr, *ncol_ptr;
	// Declare the nrow_ptr and ncol pointer
	nrow_ptr = &nrow;
	ncol_ptr = &ncol;
	// Initialized the nrow_ptr and ncol_ptr
*/   


int main(int argc, char *argv[])
{
	clrscr();
	int nMatrix;
	int nrow, ncol, nrow_1, ncol_1;
	// Number of row and column
	
	int row_loop, col_loop;
	// Loop for row and column

	int **rowptr = NULL;   // -- First Matrix
	// A pointer to pointer to integer

	int **rowptr_1 = NULL; // -- Second Matrix
	int **result = NULL;  // Result of two Matrix
	int symmetric;
	/*
	   Used while loop instead of dowhile because it's recommended
	   by Bjarne Stroustrup
	*/
// ------------------------------------------------------------
//	while(1)
//	{	// Must allocate at least two matrix
		printf("\nPlease Enter same dimension for two Matrix\n");
		printf("\nHow many Matrix : ");
		scanf("%d", &nMatrix);
		switch(nMatrix)
		{
		    case 1:
			{
				printf("How many Row : ");
				scanf("%d", &nrow);
				rowptr = (int **)malloc(sizeof(int) * nrow);
				if (rowptr == NULL)
				{
					perror("Dynamic Memory Allocation for row Fails");
				}
				printf("How many Column : ");					scanf("%d", &ncol);

				for (row_loop=0;row_loop<nrow;row_loop++)
				{
					rowptr[row_loop] = (int *)malloc(sizeof(int) * ncol);
					if (rowptr[row_loop] == NULL)
					{
						perror("Dynamic Memory Allocation for column Fails");
					}
				}

				for (row_loop=0;row_loop<nrow;row_loop++)
				{
					for (col_loop=0;col_loop<ncol;col_loop++)
					{
						printf("Enter the [%d][%d] number : ", row_loop, col_loop);
						scanf("%d", &rowptr[row_loop][col_loop]);
					}
				}
				break;
			}
// ------------------------------------------------------------
			case 2:
			{	// Enter the first matrix
				do
				{
					printf("Enter the First Matrix : \n");
					printf("How many Row : ");
					scanf("%d", &nrow);
					rowptr = (int **)malloc(sizeof(int) * nrow);
					if (rowptr == NULL)
					{
						perror("Dynamic Memory Allocation for row Fails");
					}
					printf("How many Column : ");
					scanf("%d", &ncol);

					for (row_loop=0;row_loop<nrow;row_loop++)
					{
						rowptr[row_loop] =(int *) malloc(sizeof(int) * ncol);
						if (rowptr[row_loop] == NULL)
						{
							perror("Dynamic Memory Allocation for column Fails");
						}
					}

					for (row_loop=0;row_loop<nrow;row_loop++)
					{
						for (col_loop=0;col_loop<ncol;col_loop++)
						{
							printf("Enter the [%d][%d] number : ", row_loop, col_loop);
							scanf("%d", &rowptr[row_loop][col_loop]);
						}
					}
// -----------------------------------------------------------
					// Enter the second Matrix
					printf("Enter the Second Matrix : \n");
					printf("How many row : ");
					scanf("%d", &nrow_1);
					rowptr_1 = (int **)malloc(sizeof(int) * nrow_1);
					if (rowptr_1 == NULL)
					{
						perror("Dynamic Memory Allocation Matrix 2 for row Fails");
					}
					printf("How many Column : ");
					scanf("%d", &ncol_1);

					for (row_loop=0;row_loop<nrow_1;row_loop++)
					{
						rowptr_1[row_loop] = (int*)malloc(sizeof(int) * nrow_1);
						if(rowptr_1[row_loop] == NULL)
						{
							perror("Dynamic Memory Allocation Matrix 2 for column Fails");
						}
					}

					for (row_loop=0;row_loop<nrow_1;row_loop++)
					{
						for (col_loop=0;col_loop<ncol_1;col_loop++)
						{
							printf("Enter the [%d][%d] number : ", row_loop, col_loop);
							scanf("%d", &rowptr_1[row_loop][col_loop]);
						}
					}
					break;
				}while(symmetric == 0);
			}
		}
// ------------------------------------------------------------
		// Check the Dimension of Two Matrix
		symmetric = Symmetric(nrow, ncol, nrow_1, ncol_1);
		if (symmetric == 1)
		{
			printf("The two Matrix is same dimension");
		}
		else
		{
			printf("The two Matrix is different dimension");
		}

	       // Runtime Error
		Add(rowptr, rowptr_1, nrow, ncol, nrow_1, ncol_1);
		// Adding the element of matrix
//		Display(result, nrow, ncol);
		// Display the result after successful allocated the memory

		free(rowptr);
		free(rowptr_1);
		free(result);
//	}


	return 0;

}
// -----------------------------------------------------------
int Symmetric(int nrow, int ncol, int nrow_1, int ncol_1)
{
	int symmetric;
	if (nrow == nrow_1 && ncol == ncol_1)
	{
		symmetric = 1;
		return symmetric;
	}
	else
	{
		symmetric = 0;
		return symmetric;
	}
}
// ------------------------------------------------------------
void Add(int **rowptr, int **rowptr_1, int nrow,
		 int ncol, int nrow_1, int ncol_1)
{
	int **result = NULL;
	result= (int **)malloc(sizeof(int) * nrow * ncol);
	int row_loop, col_loop;
	nrow = nrow_1;
	ncol = ncol_1;

	for (row_loop = 0;row_loop < nrow; row_loop++)
	{
		for (col_loop = 0; col_loop < ncol; col_loop++)
		{
//			*(*(result + row_loop) + col_loop) =  (*(*(rowptr + row_loop) + col_loop))   +  (*(*(rowptr_1 + row_loop) + col_loop));
			 result[row_loop][col_loop]=rowptr[row_loop][col_loop]+rowptr_1[row_loop][col_loop];
		}
	}
       Display(result,nrow,ncol);

}

// ------------------------------------------------------------
void Display(int **result, int nrow, int ncol)
{
	int row_loop, col_loop;
	// Loop for row and column

	for (row_loop = 0; row_loop < nrow; row_loop++)
	{
		for (col_loop = 0; col_loop < ncol; col_loop++)
		{
			printf("The value of array at [%d][%d] is %d\n", row_loop, col_loop, *(*(result + row_loop) + col_loop) );
		}
	}

}

// ------------------------------------------------------------
0
wrecker's Avatar, Join Date: Mar 2007
Go4Expert Member
I font understand whether you guys are actually famaliar with synataxes.
while allocating you should know that malloc returns null pointer so that has to be typecasted.
n you people straightway write mlloc(...);
Try not to repeat. Any newbie reading this would get confused and get ample errors to get his head scratched...
0
DaWei's Avatar, Join Date: Dec 2006
Team Leader
Malloc only returns a NULL pointer if it fails. Otherwise, in C (not C++), it returns a void pointer which needs to be cast.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by Peter_APIIT
Hello all expert C programmer especially shabbir
Probably I am the last one to be replying but I would suggest or expect not to direct to any one but to the programmers as a whole.
0
Peter_APIIT's Avatar, Join Date: Apr 2007
Contributor
For the older compiler(K&R), you need cast the void pointer to the type data you pointed to but for modern compiler, you doesn't need to cast the void pointer to the type of data the pointing to.

I don't know whether this is true. I just guess. I abg your pardon if my opinion make you angry.

Thanks for all replies.

Your help and replies is greatly appreciated by me and others.
0
Peter_APIIT's Avatar, Join Date: Apr 2007
Contributor
Sorry shabbir, i won't do that again. Thank for your remind.
0
Peter_APIIT's Avatar, Join Date: Apr 2007
Contributor
Hello all, i have successfully run the program but i not really understand two statement in the program.

The two statement is as below;

1. rowptr = (int **)malloc(sizeof(int **) * nrow);

Allocate nrow of array of pointer - where if nrow = 5.
The above statement is same as int *rowptr[5]; -- I don't know whether is it correct or not.

2. for (row_loop=0;row_loop<nrow;row_loop++)
{
rowptr[row_loop] = (int *)malloc(sizeof(int *) * ncol);
}

For each rowptr, allocate int * pointer pointing to ncol.

I don't know whether my understanding is correct or not. Please confirm with me whether my understanding is correct or not.


Thanks for your help.
Your help is greatly appreciated by me and others.

I don't know how to return the help you all have give. By the way, i just know say thanks to you all. Without you all, i think i not able to solve this program. This program is not assignment nor project. I just practiced it on my own.

Thanks.
Thanks.
Thanks.
Thanks.
Thanks.
Thanks.
Thanks.
Thanks.
0
wrecker's Avatar, Join Date: Mar 2007
Go4Expert Member
Ya thanks DaWei, i meant to say void pointer, but was just a mistake that i wrote null pointer. Thanks for correction..