I'm trying to add an array called shape inside a struct but once I add it and try to access the member values, it produces a segmentation fault. If I remove it, the program works perfectly.
This is the struct definition:
struct coo_matrix{
int nnz;
int shape[2];
int * rows;
int * columns;
int * values;
};
typedef struct coo_matrix * COOMatrix;
This is the function where I try to access values:
COOMatrix coo_matrix_create(int m, int sparse_matrix[][m]){
...
COOMatrix coo;
coo = malloc(sizeof(COOMatrix));
coo->rows = malloc(n * m * sizeof(int));
coo->columns = malloc(n * m * sizeof(int));
coo->values = malloc(n * m * sizeof(int));
....
....
coo->rows[k] = i;
coo->columns[k] = j;
coo->values[k] = sparse_matrix[i][j]; // see Note
....
return coo;
}
Note: Once I add shape, this line produces a segmentation fault.
PS: No need to say I am not very familiar with C, I learned other languages before I ever touched C recently.
COOMatrixandcoo_matrixare different things. you haven't shown anytypedefs here.typdefing pointers is bound to get you into trouble.sizeof(COOMatrix)in all allocations? You needsizeof(struct coo_matrix), or better,sizeof *coofor the first allocation.