Dynamic Memory Allocation for Matrix(2D Array)

Discussion in 'C' started by Peter_APIIT, Apr 16, 2007.

  1. Peter_APIIT

    Peter_APIIT New Member

    Joined:
    Apr 11, 2007
    Messages:
    92
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Malaysia
    Thanks for your replies. By the way, i not really understand why u say you are not free all the memory. You did it very well. My problem is the allcoation successfull at allocate function but when come back to main the rowptr and rowptr_1 become NULL. I don't know why.

    The swap done it well but i don't.

    Thanks for your replies.
     
  2. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    http://www.daweidesigns.com
    I don't understand what you mean by
    You aren't USING an allocation function. You are allocating directly in main.

    IF YOU ARE USING SOME CODE WHICH YOU ARE NOT SHOWING, THEN DON'T SHOW THE CODE YOU ARE NOT USING, BUT THE CODE THAT IS FAILING!!!!

    I AM NOT going to play guessing games with you. Present your problem in a sensible way.

    IF you are trying to use your Allocate function, INSTEAD of the code in main, then SHOW HOW YOU ARE CALLING IT. The function that you show makes NO arrangements for passing the rowpointers back to main and main shows NO arrangements to pass pointers to rowpointers which can be set by the function. Everything in the function concerning the rowpointers is a local variable and will disappear (quite normally, I assure you) when the function returns.
     
    Last edited: Apr 24, 2007
  3. Peter_APIIT

    Peter_APIIT New Member

    Joined:
    Apr 11, 2007
    Messages:
    92
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Malaysia
    Is it ok i post the entire code ? Then, you will understand what i mean.

    I bag your pardon.
     
  4. Peter_APIIT

    Peter_APIIT New Member

    Joined:
    Apr 11, 2007
    Messages:
    92
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Malaysia
    I have a function called allocation uses to allocated memory for rowptr and rowptr_1. The operation of allocation memory for rowptr and rowptr_1 is successful but after the allocation function finished its job, return back to main. The rowptr and rowptr_1 become NULL.

    I have review it from the debugging process, the error messa ge is cannot evaluate the expression.
     
  5. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    http://www.daweidesigns.com
    Zip up your CURRENT code, as in the code that fails, and attach it to your post. Don't include any huge blocks that are commented out, and don't include any functions that aren't actually called. The stuff is hard enough to read. One hopes, coming out the other side of this, that you will have learned how to rationally whittle down your code to the parts that actually have an effect on the operation that is failing. I supect that you are having scope resolution issues, but we shall see.
     
  6. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Thats one way but then there is trade off that you are asking people to download and see and I would add that you apply your judgement.

    I would add the files and not file as attachment and have the file content in the post as a reference something like

    I am having trouble in some function
    Code:
    SomeFunction
    Which is used from
    Code:
    SomeOtherFunctionsLikeThis
    and for your reference here is complete flow of program
    Code:
    main()
     
  7. Peter_APIIT

    Peter_APIIT New Member

    Joined:
    Apr 11, 2007
    Messages:
    92
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Malaysia
    I bag your pardon shabbir. I will remember forever. I will do it two method as mentioned by dawei and shabbir.

    Thanks for your taught. I will remember forever.
     
  8. Peter_APIIT

    Peter_APIIT New Member

    Joined:
    Apr 11, 2007
    Messages:
    92
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Malaysia
    That's true. I think i might having scope problem.

    This problem occurs here.
    Code:
    Allocate(nMatrix, nrowptr, ncolptr, nrow_1ptr, ncol_1ptr);
    Add(rowptr, rowptr_1, nrowptr, ncolptr);
    
    When i calling the Add function, the rowptr and rowptr_1 is NULL at main.



    Code:
    void Allocate(int nMatrix, int *nrowptr, int *ncolptr,
    			  int *nrow_1ptr, int *ncol_1ptr)
    {
    	int symmetric;
    	int row_loop, col_loop;
    	static int **rowptr;
    	static int **rowptr_1;
    
    	switch(nMatrix)
    	{
    		case 1:
    		{
    			rowptr = malloc(sizeof(int **) * (*nrowptr));
    			if (rowptr == NULL)
    			{
    				perror("Dynamic Memory Allocation for row Fails");
    			}	
    			
    			for (row_loop = 0;row_loop < (*nrowptr); row_loop++)
    			{
    				rowptr[row_loop] = malloc(sizeof(int *) * (*ncolptr));
    				if (rowptr[row_loop] == NULL)
    				{	
    					perror("Dynamic Memory Allocation for column Fails");
    				}
    			}
    
    			for (row_loop = 0; row_loop < (*nrowptr); row_loop++)
    			{
    				for (col_loop = 0; col_loop < (*ncolptr); 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("\nEnter the First Matrix : \n");
    				// Allocate memory for rowptr **
    				// if nrow == 3, then same as rowptr *[3]
    				rowptr = malloc(sizeof(int **) * (*nrowptr));
    				if (rowptr == NULL)
    				{
    					perror("Dynamic Memory Allocation for row Fails");
    				}	
    					
    				// For each rowptr * , allocate ncolumn
    				for (row_loop = 0;row_loop < (*nrowptr); row_loop++)
    				{
    					rowptr[row_loop] = malloc(sizeof(int *) * (*ncolptr));
    					if (rowptr[row_loop] == NULL)
    					{
    						perror("Dynamic Memory Allocation for column Fails");
    					}
    				}
    
    				for (row_loop = 0; row_loop < (*nrowptr); row_loop++)
    				{
    					for (col_loop = 0; col_loop < (*ncolptr); 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");
    					
    				// Allocate memory for rowptr_1 **
    				// if nrow == 3, then same as rowptr_1 *[3]
    				rowptr_1 = malloc(sizeof(int **) * (*nrow_1ptr));
    				if (rowptr_1 == NULL)
    				{
    					perror("Dynamic Memory Allocation Matrix 2 for row Fails");
    				}
    					
    				// For each rowptr_1 * , allocate ncolumn
    				for (row_loop = 0; row_loop < (*nrow_1ptr); row_loop++)
    				{
    					rowptr_1[row_loop] = malloc(sizeof(int *) * (*ncol_1ptr));
    					if(rowptr_1[row_loop] == NULL)
    					{
    						perror("Dynamic Memory Allocation Matrix 2 for column Fails");
    					}
    				}
    					
    				for (row_loop = 0; row_loop < (*nrow_1ptr); row_loop++)
    				{
    					for (col_loop = 0; col_loop < (*ncol_1ptr); col_loop++)
    					{
    						printf("Enter the [%d][%d] number : ", row_loop, col_loop);
    						scanf("%d", &rowptr_1[row_loop][col_loop]);
    					}
    				}
    					
    				// Check the Dimension of Two Matrix
    				symmetric = Symmetric(nrowptr, ncolptr, nrow_1ptr, ncol_1ptr);
    				if (symmetric == 1)
    				{
    					printf("The two Matrix is same dimension");
    				}
    				else
    				{
    					printf("The two Matrix is different dimension");
    				}
    			}while(symmetric == 0);
    			break;
    		}
    	}
    }
    // ------------------------------------------------------------
    int Symmetric(int *nrowptr, int *ncolptr, 
    			  int *nrow_1ptr, int *ncol_1ptr)
    {
    	int symmetric;
    	if ((*nrowptr) == (*nrow_1ptr) && (*ncolptr) == (*ncol_1ptr))
    	{
    		symmetric = 1;
    		return symmetric;
    	}
    	else
    	{
    		symmetric = 0;
    		return symmetric;
    	}
    }
    
    
    
    The allocation is successful but when arrived at main, the rowptr and rowptr_1 become NULL.

    I think this might clarify what i want more clearly.
    Thanks for your help.

    Your help is greatly appreciated by me and others.
     

    Attached Files:

  9. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    http://www.daweidesigns.com
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef int** matBegin;
    typedef struct sMatrix *pMatrix;
    typedef struct sMatrix
    {
        unsigned rows;
        unsigned cols;
        matBegin begin;
    } matrix;
    
    void demoFill (pMatrix matrix)
    {
        unsigned i, j;
        for (i = 0; i < matrix->rows; ++i)
        {
            for (j = 0; j < matrix->cols; ++j)
            {
    	        matrix->begin[i][j] = i*10 + j;
            }
        }
    }
    
    void displayMatrix (pMatrix matrix)
    {
        unsigned i, j;
        printf ("\n");
        for (i = 0; i < matrix->rows; ++i)
        {
    	    for (j = 0; j < matrix->cols; ++j)
    	    {
    		    printf ("%02d ", matrix->begin[i][j]);
    	    }
    	    printf ("\n");
        }
        printf ("\n");
    
    }
    
    matBegin allocateMatrix (pMatrix matrix, unsigned rows, unsigned cols)
    {
        unsigned i;
        int mallocFail = 0;
    
        matrix->begin = malloc (sizeof (*matrix->begin) * rows);
        if (matrix->begin == NULL) return NULL;
        memset (matrix->begin, 0, sizeof (*matrix->begin) * rows);
        matrix->cols = cols;
        matrix->rows = rows;
        for (i = 0; (i < rows) && (!mallocFail); ++i)
        {
            matrix->begin [i] = malloc (cols * sizeof (int));
            if (!matrix->begin [i]) mallocFail = 1;
        }
        if (mallocFail)
        {
            for (i = 0; i < rows; ++i) free (matrix->begin [i]);
            matrix->cols = 0;
            matrix->rows = 0;
            free (matrix->begin);
            matrix->begin = NULL;
        }
        return matrix->begin;
    }
    int badNews (char *trouble)
    {
        fprintf (stderr, "%s\n", trouble);
        return -1;
    }
    int main (int argc, char *argv[])
    {
        matrix firstMatrix;
        matrix secondMatrix;
        matBegin pFirst;
        matBegin pSecond;
    
        pFirst = allocateMatrix (&firstMatrix, 3, 4);
        if (pFirst == NULL) return badNews ("Malloc failed");
        pSecond = allocateMatrix (&secondMatrix, 4, 5);
        if (pSecond == NULL) return badNews ("Malloc failed");
    
        demoFill (&firstMatrix);
        demoFill (&secondMatrix);
    
        displayMatrix (&firstMatrix);
        displayMatrix (&secondMatrix);
    
        return 0;
    }
    
     
  10. Peter_APIIT

    Peter_APIIT New Member

    Joined:
    Apr 11, 2007
    Messages:
    92
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Malaysia
    I not really understand the program. What the difference your program and my program ?

    Thanks for your help.
     
  11. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    http://www.daweidesigns.com
    If you don't see the difference, I recommend that you run a 'diff' program over the code. If you see the difference, but don't understand it, then I recommend that you ask a specific question.

    I have previously recommended that you investigate scope, particularly as it relates to auto variables. One may attempt to avoid the drawbacks of automatic variables by resorting to global or static keywords, but such measures are often dangerous and ineffective.

    At some point in this exercise, you are going to have to go sit behind the barn and watch the cotton grow while you reflect on the realities of the language. Take a reference book with you.
     
  12. Peter_APIIT

    Peter_APIIT New Member

    Joined:
    Apr 11, 2007
    Messages:
    92
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Malaysia
    I don't like spoon feeding because i learn nothing. My program has scope problem. Please tell me exact error and the method to solve it and not just posting the code.

    Thanks.
     
  13. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    http://www.daweidesigns.com
    What you have been getting here is not spoon feeding. You've been advised to post in certain ways that help your respondents. You persist in ignoring those suggestions. You've been advised to read the posts with attention and think about them. You apparently don't do that. Rather, you advise US on how we should spend our (free) time in advising you, which amounts precisely to spoon-feeding. As is my prerogative, I choose not to participate on your terms; nor will I offer more.
     
  14. Peter_APIIT

    Peter_APIIT New Member

    Joined:
    Apr 11, 2007
    Messages:
    92
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Malaysia
    I bag your pardon. Without bothering the problem this again, what wrongs with my program.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice