My task is to write a function int *matrica1(int n)
. This function must create a matrix dimensions nxn and then you have to allocate its memory and in the main you have to write the elements of the matrix. I have a problem when returning pointer mat1
to **p
and when i call **p
i get a address instead of a number but when i call **mat1
in the function i get the number. I do not understand ?
#include <stdio.h>
int *matrica1(int n);
int main(){
int n;
printf("Input dimension of matrix:");
scanf("%d", &n);
int **p = matrica1(n);
printf("Matrix \n\n");
int i;
n = n*n;
for(i=0; i<n; i++){
printf(" %d ", **(p+i));//I keep getting an address
}
return 0;
}
int *matrica1(int n){
int mat[n][n];
int i, j;
int k=0;
for(i=0; i<n; i++){
for(j=0; j<n; j++){
mat[i][j] = j+k;
}
k++;
}
int size = n*n;
int **mat1 = (int*)malloc(size*sizeof(int));
int m = 0;
for(i=0; i<n; i++){
for(j=0; j<n; j++){
mat1[m] = &mat[i][j];
m++;
}
}
printf("\n\n**mat1 = %d", **mat1);//Here it returns me a number
return mat1;
}