對於我正在做的關於C中指針的練習,我想通過將指針listStart發送到insertEntry函數以及我想要插入的結構來在鏈表的開始處插入結構。然而,對於這個當前的代碼,我無法做到這一點,因爲listStart指針並沒有攜帶它在主函數(列表的第一個結構)中指向的地址。發送列表指針到函數
據我所知,我只是將指針本身複製到insertEntry函數中,因此它指向的地址被省略。這意味着我所得到的insertEntry函數中的listStart指針是一個空指針。
爲了解決這個問題,我嘗試將listStart作爲指針發送給insertEntry函數,但是,它只是給了我指向指向null的指針的指針。我試着將listStart的地址發送給那個不工作的函數,因爲它是向函數發送null的。
我有問題:是否有可能做到這一點,我只是錯過了什麼?或者這是不可能的?
謝謝先進。
// header to include standard input and output
#include <stdio.h>
struct entry
{
int value;
struct entry *next;
};
// prototype for insertEntry function
void insertEntry(struct entry *l, struct entry *i, struct entry *j);
int main(void)
{
// declaration of array for linked list
struct entry list1 = { 1 }, list2 = { 2 }, list3 = { 3 }, list4 = { 4 }, list5 = { 5 }, insert = { 8 };
struct entry *listStart = &list1;
// test to see if the value of the insert.value struct is correct
printf("insert.value = %i\n", insert.value);
// assign pointers in list.next to the next struct in the list to create a linked list
list1.next = &list2;
list2.next = &list3;
list3.next = &list4;
list4.next = &list5;
list5.next = (struct entry *) 0;
// print the linked list to make sure the pointers are going to the correct struct member
printf("Original list!\n");
while (listStart != (struct entry *) 0)
{
printf ("%i\n", listStart->value);
listStart = listStart->next;
}
// send struct to change and struct to insert
insertEntry(listStart, &insert, &list1);
// restart the list from the beginning because in the last while loop the listStart was assigned to the null pointer.
listStart = &list1;
// print the new list to show what has been inserted and moved around
printf("New list!\n");
while (listStart != (struct entry *) 0)
{
printf ("%i\n", listStart->value);
listStart = listStart->next;
}
return 0;
}
// function to insert a new struct in the list and redirect an old struct in the list
void insertEntry(struct entry *l, struct entry *i, struct entry *j)
{
i->next = l; // this is assigning the mem add of the pointer is list2.next to that of insert.next
l = i; // this is assigning the mem add of i which would be insert.value to the pointer in list2.next
}
*捂臉*杜!感謝所有回答! – alucinare