c - 链表的二维数组

标签 c memory linked-list

我正在尝试创建一个二维链表来保存稀疏矩阵,并编写了以下代码以在正确的位置插入一个新节点:

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 错误,而上一行则没有,我不完全确定原因。谁能看出发生这种情况的原因吗?

最佳答案

这可能只是程序中其他地方的问题,涉及行数据的分配/维护方式,而列数据恰好没问题。您检查过 rowHead 的值吗?也许它是 null 或垃圾值...然后您可以从那里追溯以找出这是如何发生的。

关于c - 链表的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14527384/

相关文章:

c - nginx 内存池损坏?

objective-c - 如何搜索有关数值宏的文档?

javascript - Three.js/WebGL一次加载大量纹理数据,如何处理?

c - 如何使用指向指针的指针插入链表

C - 链表 - 以相反的方式链接

c - 如何正确释放一个 erlang 术语

检查缓冲区中是否有重复的数组

C# 字符* 到字符串

c++ - CMake:使用 target_compile_options 设置 ggc-min-expand 和 -heapsize

将结构元素与c中的整数进行比较