2017-01-29 183 views
1

如何更改list_pointer的开始?我试图通过比较两个指针来实现这一点。但它只能在一种功能中起作用。C中的指针通过函数更改列表指针的开始

或者我需要创建新的结构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; 
} 

回答

2

list_pointer是本地insertEntry。并且修改其值(这是一个地址)将不会反映在您在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 
    } 

} 

我省略了NULL支票上p_list_pointer,但这是它的要点。

+0

谢谢! @说故事的人 – Yellowfun