I’m trying to create a two dimensional linked list to hold a sparse matrix and have written this code to insert a new node at the right place:
void insertNewNode(node **rowHead, node **columnHead, int value, int row, int column) {
//Get to the correct position in the column linked list
if (*columnHead == NULL) {
*columnHead = malloc(sizeof(node));
} else {
while((*columnHead)->nextColumn != NULL && (*columnHead)->nextColumn->row < row)
*columnHead = (*columnHead)->nextColumn;
}
//Get to the correct position in the row linked list.
if (*rowHead == NULL) {
*rowHead = malloc(sizeof(node));
} else {
while((*rowHead)->nextRow != NULL && ((*rowHead)->nextRow->column < column))
*rowHead = (*rowHead)->nextRow;
}
node *newNode = malloc(sizeof(node));
newNode->column = column;
newNode->row = row;
newNode->value = value;
(*columnHead)->nextColumn = newNode;
(*rowHead)->nextRow = newNode;
}
For some reason the last line:
(*rowHead)->nextRow = newNode;
is causing an EXC_BAD_ACCESS error while the previous line is not, and I’m not entirely sure why. Can anyone see a reason why this would occur?
It could just be a problem somewhere else in your program with how your row data is allocated/maintained, and your column data happens to be OK. Have you inspected the value of rowHead? Maybe it is null or a garbage value… then you can trace back from there to figure out how that is happening.