+ Reply to Thread
Results 1 to 2 of 2

Thread: How to create two dimensional array using new in C++?

  1. #1

    How to create two dimensional array using new in C++?

    Hi All,

    How to create two dimensional array using new keyword and destroy the object using delete in C++?

    Regards.

  2. #2
    Hi,

    Below is example:

    Code:
    unsigned char ** GetTwoDimensionalArray(int nRows, int nColumns)
    {
        unsigned char ** ppImageArray ;
    
        ppImageArray = new unsigned char *[nRows] ;
    
        for (int nRowIndex = 0; nRowIndex < nRows; nRowIndex++)  
    	{
           ppImageArray[nRowIndex] = new unsigned char[nColumns] ;
    	}
    
    	return ppImageArray ;
    }
    
    void DeleteTwoDimensionalArray(unsigned char **ppImageArray, int nRows)
    {
    	for (int nRowIndex = 0; nRowIndex < nRows; nRowIndex++)  
    	{
           delete(ppImageArray[nRowIndex]) ;
    	}
    
    	delete(ppImageArray) ;
    }
    
    void UseTwoDimensionArray()
    {
    #define ROWS	2
    #define COLUMNS	3
    
    	unsigned char **ppImageArray = GetTwoDimensionalArray(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") ;
    	}
    
    	DeleteTwoDimensionalArray(ppImageArray, ROWS) ;
    }
    Hope this helps.

    Thanks.

+ 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