Home > My Original Post > 2D dynamic array for arbitrary image size – C/C++ implementation

2D dynamic array for arbitrary image size – C/C++ implementation

If we would like to read an arbitrary size image and do processing algorithms, fixed size 2D data array is not applicable. A dynamic allocating technique is using malloc function.

It is easier to malloc 1D array into a heap. But this will result in harder works for indexing the 1D array since an image is 2D.

Thus we have to do the following code to allocate 2D dynamic array in a heap within a subroutine function, which can be called in main function. Never forget to free the heap after use to prevent from memory leak.

unsigned char * bndfollow(unsigned char *in, int m,int n)
{
 int i,j;
 //allocating dynamic 2D array - input data array
 unsigned char** data_in=(unsigned char**)malloc(sizeof(unsigned char *) * m);//new int*[m];
 data_in[0] = (unsigned char *)malloc(sizeof(unsigned char) * m * n);//allocating memory continuously
 for(i=0; i<m; i++)
 {
   data_in[i+1] = data_in[i] + n;
 }

 for(i=0;i<m;i++)
 {
   for (j=0;j<n;j++)
   {
     data_in[i][j]=0;
  // printf("%d ", data_in[i][j]);
   }
 }

 for(i=0;i<m;i++)
 {
   for (j=0;j<n;j++)
   {
     data_in[i][j]=in[i*n+j];//initializing all elements
  // printf("%d ", data_in[i][j]);
   }
 }

// processing data_in[][]

//...

// put output data to data_out[][]

//allocating dynamic 2D array, output
 unsigned char** data_out=(unsigned char**)malloc(sizeof(unsigned char *) * m);//new int*[m];
 data_out[0] = (unsigned char *)malloc(sizeof(unsigned char) * m * n);//
 for(i=1; i<m; i++)
 {
   data_out[i] = data_out[i-1] + n;
 }
 for(i=0;i<m;i++)
 {
   for (j=0;j<n;j++)
   {
     data_out[i][j]=0;
  // printf("%d ", data_in[i][j]);
   }
 }
 //put bound data to output array

 for(i=0;i<m;i++)
 {
   for (j=0;j<n;j++)
   {
     data_out[i][j]=data_scan1[i][j]*255;
   }

 }

 return &data_out[0][0];// return the heap pointer
}
int main()
{

 //calling the subroutine

 unsigned char *book_bnd=bndfollow(&book_rot[0][0],256,256);

 //...

}
Advertisements
Categories: My Original Post
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: