Search code examples
cdynamicmatrixallocation

How to dynamically allocate a matrix in C?


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:

  • Serialize: given the "M" matrix it return the list L with n^2 elements. The elements of the list are the element of M ordered by row from the first to the second.

The second function:

  • Deserialize: given the list L with n^2 elements, it return a matrix [nxn] with elements of L ordered by column.

So main() must be:

  • User give the dimension of matrix (n) and fill the matrix with some integer.
  • Then call serialize function, print the list serialized
  • add the value 5 to every value of list
  • and call deserialize function
  • and print the matrix given by the last function.

(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?


Solution

  • 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);