Reputation: 23
#include<stdio.h>
#include<stdlib.h>
int **transpose(int a[], int b[], int raw, int column){
int i, j;
for(i=0; i < raw ; i++)
for(j=0; j < column ; j++)
*(b+(j*raw + i)) = *(a+(i*column + j));
return *b;
}
int **mk_matrix(int raw, int col){
int i;
int **matrix = (int**)malloc(sizeof(int*)*raw);
matrix[0] = (int*)malloc(sizeof(int)*(raw*col));
for(i=1 ; i < raw ; i++)
matrix[i] = matrix[i-1] + col;
return matrix;
}
void main(void){
int r, c, i, j;
printf("Input the size of matrix : ");
scanf("%d %d", &r, &c);
int **matrix = mk_matrix(r, c);
int **trans_matrix = mk_matrix(c, r);
printf("Input elements of the %dx%d matrix : ", r, c);
for(i=0; i < r ; i++)
for(j=0; j < c ; j++)
scanf("%d", &matrix[i][j]);
**trans_matrix = transpose(matrix[0], trans_matrix[0], r, c);
for(i=0; i < c ; i++){
for(j=0; j < r ; j++)
printf("%d ", trans_matrix[i][j]);
printf("\n");
}
}
In dev c++, this code runs correctly by I wanted but it comes
How can i fix my code not showing warnings?
Upvotes: 2
Views: 149
Reputation: 1153
In the function transpose()
you are returning a ptr to int
when the return type of transpose()
is ptr to ptr to int
. Now because you are returning the value of the wrong (not expected) data type, you are getting your second warning.
Another thing is when you are working with addresses of the matrices in the transpose()
function you don't need to return
any kind of value because ultimately you are changing values that are stored on that address. You are not working on a copy of that value. That's why you don't need to:
**trans_matrix = transpose(matrix[0], trans_matrix[0], r, c);
I don't know why you are overcomplicating the functions. You can write them as:
int transpose(int **a, int **b, int row, int column)
{
int i, j;
for(i=0; i < column ; i++)
for(j=0; j < row ; j++)
b[i][j] = a[j][i];
return 0;
}
and
int **mk_matrix(int row, int col)
{
int i;
int **matrix = malloc(sizeof(int*)*row);
for(i=0; i<row; i++)
matrix[i] = malloc(sizeof(int)*(col));
return matrix;
}
and in main()
you just need to modify how you call the transpose()
method:
transpose(matrix, trans_matrix, r, c);
P.S. Also, check if the memory space you are requesting(malloc()
) is allocated to the ptr or not.
Upvotes: 1
Reputation: 294
Well you don't need to
return *b
int **transpose(int a[], int b[], int raw, int column)
just modify above to
void transpose(int a[], int b[], int raw, int column){
int i, j;
for(i=0; i < raw ; i++)
for(j=0; j < column ; j++)
*(b+(j*raw + i)) = *(a+(i*column + j));
}
and in main function
**trans_matrix = transpose(matrix[0], trans_matrix[0], r, c);
to
transpose(matrix[0], trans_matrix[0], r, c);
as transpose function is already performing necessary changes to trans_matrix. You do not need to return.
this will resolve warning issue.
Upvotes: 3