2011-12-02 28 views
2

考慮下面的代碼,試圖使Sparse_matrix包含一個指針數組。在「結構Sparse_matrix」,這是一個正確的方式來創建一個指針數組時大小未知?什麼是C程序員解決這個問題的方法?我是新來的C.當尺寸未知時,創建一個指針數組(稀疏矩陣)

感謝您的幫助

#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; 
} 

回答

1

最好寫

SparseMatrix* matrix=malloc(cols*sizeof(Node*)+sizeof(SparseMatrix)); 
因爲路線的

和差距