Search code examples
csparse-matrix

Create an array of pointer when size is unknown(sparse-matrix)


consider the code below, Am trying to make a Sparse_matrix that contains an array of pointer. In "struct Sparse_matrix", Is this a proper way to create a pointer array when size is unknown? What's the C programmer way to solve this? I'm new to C.

Thanks for help

#include "sparse_matrix.h"
struct Node{
    short data;
    unsigned short row;
    Node* next;
};

struct SPARSE_MATRIX {
    unsigned short cols;
    Node* list[0];
};

SparseMatrix *create(unsigned short rows, unsigned short cols){
    SparseMatrix* matrix=malloc(cols*sizeof(Node*)+sizeof(unsigned short));
    matrix->cols=cols;

    for(int i=0;i<cols;i++){
        matrix->list[i]=NULL;
    }
    return matrix;
}

Solution

  • Better write

      SparseMatrix* matrix=malloc(cols*sizeof(Node*)+sizeof(SparseMatrix));
    

    because of alignments and gaps