C struct指针作为参数:对struct进行永久更改

syphjos

这段代码试图按优先级对一系列节点进行排序,事实是,我从函数返回的结果是对节点进行排序的,我所做的任何事情都不会持久化。这是我的简单代码,下面是输出。

#include <stdio.h>
#include <stdlib.h>
#define null 0

typedef struct NODE{
    struct NODE * next;
    struct NODE * prev;
    int priority;
}NODE;

struct NODE nodes[5];

struct NODE * head = null;

NODE * function( NODE * pHead,  NODE * top){

     NODE * pos = top;

    if(top == null){
        top = pHead;
    }
    else{
        if(top->priority < pHead->priority){
            top = pHead;
            pHead->prev = pos->prev;
            pHead->next = pos;
            pos->prev = pHead;
        }
        while(pHead->priority < pos->priority){
            pos = pos->next;
            if(pos == null){
                pos->next = pHead;
                pHead->prev = pos;
                pHead->next = null;
                return top;
            }
        }
        (pos->prev)->next = pHead;
        pHead->prev = pos->prev;
        pHead->next = pos;
        pos->prev = pHead;  

    }
    return top;
}
void printNodes(){
     NODE * pos = head;
    while(pos != null){
        printf("PRIORITY ORDER!:::::%d\n", pos->priority);
        pos = pos->next;
    }
}
int main(){

    nodes[0].priority = 10;
    nodes[1].priority = 9;
    nodes[2].priority = 8;
    nodes[3].priority = 7;
    nodes[4].priority = 6;

    nodes[0].next = null;
    nodes[1].next = null;
    nodes[2].next = null;
    nodes[3].next = null;
    nodes[4].next = null;

    nodes[0].prev = null;
    nodes[1].prev = null;
    nodes[2].prev = null;
    nodes[3].prev = null;
    nodes[4].prev = null;

    head = function(&nodes[0], head);
    printf("HEAD %p\n", head);
    printf("PRIORITY ORDER!:::::%d\n", head->priority);
    head = function(&nodes[1], head);
    printf("PRIORITY ORDER!:::::%d\n", head->priority);
    head = function(&nodes[2], head);
    printf("PRIORITY ORDER!:::::%d\n", head->priority);
    head = function(&nodes[3], head);
    printf("PRIORITY ORDER!:::::%d\n", head->priority);
    head = function(&nodes[4], head);
    printf("PRIORITY ORDER!:::::%d\n", head->priority);

    printNodes();

    return 0;
}

输出:

HEAD 0x600c20
PRIORITY ORDER!:::::10
Segmentation fault (core dumped)
毫米

该段故障是由以下原因引起的:

if(pos == null){
     pos->next = pHead;

您取消引用空指针。

由于变量名称不一致(下一个节点top是,head并且pHead是下一个节点,等等),我在遵循您的代码时遇到麻烦

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章