c - C中的指针。通过函数更改列表指针的开头

标签 c list pointers

如何更改 list_pointer 的开头?我试图通过比较两个指针来实现这一点。但它只能在一个函数内工作。

或者我需要为 exmple struct entry head 创建新结构?

// Function to insert a new entry into a linked list. 
#include <stdio.h>

struct entry
{
    int            value;
    struct entry   *next;
};

void insertEntry(struct entry *insertion, struct entry *previous, struct entry *list_pointer)
{   //               1   <           100
    if (insertion->value < previous->value) {
        //         n0   =    n1
        insertion->next = previous;
        //           =  n0     // start from n0 insted of n1
        list_pointer = insertion;
        // list_pointer is set to point to n0 only here inside this fuction  
    }
    else {
        insertion->next = previous->next; // set n2_3.next to point to whatever n2.next was pointing to
        previous->next = insertion;       // set n2.next to point to n2_3
    }

}

void printPlist(struct entry *list_pointer)
{
    while (list_pointer != (struct entry *) 0) {
        printf("%i\n", list_pointer->value);
        list_pointer = list_pointer->next;
    }
    printf("\n");
}

int main(void)
{
    struct entry n3 = { .value = 300,.next = (struct entry *) 0 };
    struct entry n2 = { .value = 200,.next = &n3 };
    struct entry n1 = { .value = 100,.next = &n2 };
    struct entry *list_pointer = &n1;

    //struct entry n2_3 = { .value = 250 }; // insertion
    struct entry n0 = { .value = 1 }; // insertion

    printPlist(list_pointer);
    insertEntry(&n0, &n1, list_pointer);
    printPlist(list_pointer);

    return 0;
}

最佳答案

list_pointer 对于 insertEntry 是本地的。并且对其值(地址)的修改不会反射(reflect)在您在 main 中定义的 list_pointer 中。

与往常一样,您需要传递一个指向您希望修改的变量的指针。如果变量是指针,则需要是指向指针的指针:

void insertEntry(struct entry *insertion, struct entry *previous, struct entry **p_list_pointer)
{   //               1   <           100
    if (insertion->value < previous->value) {
        //         n0   =    n1
        insertion->next = previous;
        //           =  n0     // start from n0 insted of n1
        *p_list_pointer = insertion;
        // list_pointer is set to point to n0 only here inside this fuction  
    }
    else {
        insertion->next = previous->next; // set n2_3.next to point to whatever n2.next was pointing to
        previous->next = insertion;       // set n2.next to point to n2_3
    }

}

我省略了对 p_list_pointer 的 NULL 检查,但这就是它的要点。

关于c - C中的指针。通过函数更改列表指针的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41918988/

相关文章:

swift - Swift 中的指针和 malloc

C: double == -0 是什么意思?

c - PIT 不向 IRQ0 发送中断

python - 将具有多值字段的 CSV Python 列表转换为 Python 嵌套列表,对嵌套列表值进行排序并导出为 CSV

java - 对于 JAMA 或其他库,将 List<List<Double>> 转换为 double[][]

python - 如何获取特定元素后的字典键的长度?

c - 如何在我的 C 代码中修复此段错误

c++ - 关闭 AF_PACKET 与 AF_INET 的时间差?

c - c 中带有指针的 fread 和 fwrite

c - 使用 (*ptr)[5] 代替 *ptr 的目的是什么?