Reputation: 13051
I have to do this exercise:
Do an application in C that manages a matrix of integer named "M" and a list of integer named "L". M is a square matrix [nxn] with n chosen by user dynamically. Then do this function:
The second function:
So main()
must be:
(All allocation must be dynamic.)
I have tried this:
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,j;
printf("Give the dimension of matrix [nxn]: ");
scanf("%d",&n);
int **M;
M = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++){
M[i] = (int*)malloc(n*sizeof(int*));
}
int *L = serialize(M,n);
int size = n*n;
for(i=0;i<size;i++){
printf("L[%d]= %d",i,L[i]);
}
for(i=0;i<size;i++){
L[i] = L[i]+5;
}
int **M2 = deserialize(L,n);
for(i=0;i<n;i++){
printf("\n");
for(j=0;j<n;j++){
printf("%d",M2[i][j]);
}
}
free(M);
free(M2);
free(L);
}
int serialize(int** M,int n){
int *L;
int i,j;
int size = n*n;
L = (int*)malloc(size*sizeof(int));
for(i =0;i<size;i++)
L[i]=M[i/size][(int)i%size];
return L;
}
int deserialize(int* L,int n){
int** M;
int i,j;
M = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++){
M[i] = (int*)malloc(n*sizeof(int*));
}
int size = n*n;
for(i=0;i<size;i++)
M[i/size][i%size]=L[i];
return **M;
}
The compiler give me the errors:
Esercizio.c: In function ‘main’:
Esercizio.c:22: warning: initialization makes pointer from integer without a cast
Esercizio.c:31: warning: initialization makes pointer from integer without a cast
Esercizio.c: At top level:
Esercizio.c:43: error: conflicting types for ‘serialize’
Esercizio.c:22: error: previous implicit declaration of ‘serialize’ was here
What can I do?
Upvotes: 1
Views: 6573
Reputation: 137322
in deserialize, you should return M
, not **M
:
int** deserialize(int* L,int n){
int** M;
//....
return M;
}
Also, you need to declare the functions before calling them. Before main
add:
int* serialize(int** M,int n);
int** deserialize(int* L,int n);
Upvotes: 3
Reputation: 258608
You forgot to declare your functions before you use them. Add
int serialize(int** M,int n);
int deserialize(int* L,int n);
before your call to main
.
Also,
int **M2 = deserialize(L,n);
M2
is an int**
, but deserialize
returns an int
. What is your intention?
Upvotes: 2