I was developing code to accept two matrices, dynamically allocate memory for them and display their sum using functions. Declaring the return types of my input,output and sum functions as 'void' resulted in a segmentation error, but, on setting the return type to 'int**' the code worked fine. I want to know what's the difference. Why was my code unable to access the elements of the matrices when the return type of the functions was 'void'?
I thought it should be able to since I had passed the pointer to the matrix as an argument to the function.
//Before changing the return type:
void input(int **x,int m,int n){
int i,j;
x=(int**)malloc(m*sizeof(int*));
for(i=0;i<m;i++){
x[i]=(int*)malloc(n*sizeof(int));
for(j=0;j<n;j++){
scanf("%d",&x[i][j]);
}
}
}
void sum(int **z,int **y,int **x,int m,int n){
int i,j;
z=(int**)malloc(m*sizeof(int*));
for(i=0;i<m;i++){
z[i]=(int*)malloc(n*sizeof(int));
for(j=0;j<n;j++){
z[i][j]=x[i][j]+y[i][j];
}
}
}
void output(int **x,int m,int n){
int i,j;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("%d ",x[i][j]);
}
printf("\n");
}
}
//After changing the return type:
int** input(int **x,int m,int n){
int i,j;
x=(int**)malloc(m*sizeof(int*));
for(i=0;i<m;i++){
x[i]=(int*)malloc(n*sizeof(int));
for(j=0;j<n;j++){
scanf("%d",&x[i][j]);
}
}
return x;
}
int** sum(int **z,int **y,int **x,int m,int n){
int i,j;
z=(int**)malloc(m*sizeof(int*));
for(i=0;i<m;i++){
z[i]=(int*)malloc(n*sizeof(int));
for(j=0;j<n;j++){
z[i][j]=x[i][j]+y[i][j];
}
}
return z;
}
void output(int **x,int m,int n){
int i,j;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("%d ",x[i][j]);
}
printf("\n");
}
}