+ Reply to Thread
Results 1 to 2 of 2

Thread: How to create two dimensional array using malloc?

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    49

    How to create two dimensional array using malloc?

    Hi all,

    I am C developer and want to create two dimensional array for my image processing work.

    How can I use malloc to create this?

    Thanks.

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    Below is sample code to create two dimensional array using malloc and free.

    Code:
    unsigned char ** GetDynamicArrayForImage(int nRows, int nColumns)
    {
        unsigned char ** ppImageArray ;
    
        ppImageArray = (unsigned char **) malloc( nRows * sizeof(unsigned char *) ) ;  
    
        for (int nRowIndex = 0; nRowIndex < nRows; nRowIndex++)  
    	{
           ppImageArray[nRowIndex] = (unsigned char *) malloc( nColumns * sizeof(unsigned char) ) ;
    	}
    
    	return ppImageArray ;
    }
    
    void DeleteImageArray(unsigned char **ppImageArray, int nRows)
    {
    	for (int nRowIndex = 0; nRowIndex < nRows; nRowIndex++)  
    	{
           free(ppImageArray[nRowIndex]) ;
    	}
    
    	free(ppImageArray) ;
    }
    
    void UseTwoDimensionArray()
    {
    #define ROWS	2
    #define COLUMNS	3
    
    	unsigned char **ppImageArray = GetDynamicArrayForImage(ROWS, COLUMNS) ;
    
    	for (int nRowIndex = 0; nRowIndex < ROWS; nRowIndex++)  
    	{
    		for (int nColumnIndex = 0; nColumnIndex < COLUMNS; nColumnIndex++)  
    		{
    			ppImageArray[nRowIndex][nColumnIndex] = (COLUMNS * nRowIndex) + nColumnIndex ;
    		}
    	}
    
    	for (nRowIndex = 0; nRowIndex < ROWS; nRowIndex++)  
    	{
    		for (int nColumnIndex = 0; nColumnIndex < COLUMNS; nColumnIndex++)  
    		{
    			printf("%d\t", ppImageArray[nRowIndex][nColumnIndex]) ;
    		}
    		printf("\n") ;
    	}
    
    	DeleteImageArray(ppImageArray, ROWS) ;
    }

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts