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




int **transpose(int **x,int m,int n);



main()
{
  int nrows=2,ncolumns=2,i,j,k=0;
  

  //memory allocation for array x
  int **array;
  array = malloc(nrows * sizeof(int *));
  if(array == NULL)
    {
      printf("out of memory\n");
      return 0;
    }

  
  for(i = 0; i < nrows; i++)
    {
      array[i] = malloc(ncolumns * sizeof(int));
      if(array[i] == NULL)
	{
	  printf("out of memory\n");
	  return 0;
	}
    }

 

 


  //define x
  printf("x=\n");
  for(i=0;i<2;i++)
    {
printf("\n");	  
  for(j=0;j<2;j++)	    
    {
      k=k+5;
      array[i][j]=i+j+k;
      printf("%d\t",array[i][j]);
    } 
    }
  printf("\n");






  //memory allocation for x_transpose, (storing the transpose returned by function)

  int **x_transpose;
  x_transpose = malloc(nrows * sizeof(int *));
  if(x_transpose == NULL)
    {
      printf("out of memory\n");
      return 0;
    }

  
  for(i = 0; i < nrows; i++)
    {
      x_transpose[i] = malloc(ncolumns * sizeof(int));
      if(x_transpose[i] == NULL)
	{
	  printf("out of memory\n");
	  return 0;
	}
    }







  //call function
  x_transpose= transpose(array,nrows,ncolumns);






  //display transpose
  printf("x_transpose=\n");
  for(i=0;i<2;i++)
    {
printf("\n");	  
  for(j=0;j<2;j++)	    
    {
      printf("%d\t",x_transpose[i][j]);
    }
    }
}









//function_transpose

int **transpose(int **x,int m,int n)
{
  int nrows=n,ncolumns=m,i,j;

  //memory allocation for y,to store transpose
  int **y;
  y = malloc(nrows * sizeof(int *));
  if(y == NULL)
    {
      printf("out of memory\n");
      return 0;
    }
  for(i = 0; i < nrows; i++)
    {
      y[i] = malloc(ncolumns * sizeof(int));
      if(y[i] == NULL)
	{
	  printf("out of memory\n");
	  return 0;
	}	  
    }




 
  for(i=0;i<m;i++)
    for(j=0;j<n;j++)
      {
	y[i][j]=x[j][i];
      }
  return y;
}

i allocated memory for storing y(transpose of matrix) inside the function. also i allocated memory(for x_transpose) for storing the same result in main program. can reuse the same memory in main also???

You don't need to allocate memory for x_transpose. After the line x_transpose= transpose(array,nrows,ncolumns); x_transpose points to the same block of memory that was allocated for y. You do need to free all of this memory before the program closes, however.

ok, then how can i declare x_transpose in main program?

You already did. Declaration: int **x_transpose; Initialization: x_transpose= transpose(array,nrows,ncolumns);

k. that helps

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.