【发布时间】:2013-01-25 17:42:24
【问题描述】:
我正在尝试创建一个二维链表来保存一个稀疏矩阵,并编写了这段代码来在正确的位置插入一个新节点:
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;
}
由于某种原因最后一行:
(*rowHead)->nextRow = newNode;
导致 EXC_BAD_ACCESS 错误,而前一行没有,我不完全确定原因。谁能看到会发生这种情况的原因?
【问题讨论】:
-
你的
typedef节点在哪里? -
typedef struct node { int value, row, column;结构节点 *nextColumn;结构节点 *nextRow; } 节点;
-
你在测试 malloc 的 NULL 吗? (在调试期间左右?)
-
你是如何测试这个的?
-
信息太少,我们不知道问题所在。
标签: c memory linked-list