对于我在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
}
问题1
您正在更改listStart
第一个while
循环中指向的位置。在这个循环结束,值listStart
是NULL
。
我建议您使用其他变量来遍历列表项,并始终listStart
指向列表的开头。
struct entry *iter = listStart;
while ( iter != NULL )
{
printf ("%i\n", iter->value);
iter = iter->next;
}
iter
在两个循环中使用可以始终listStart
指向列表的开头。
问题2
调用之后insertEntry
,listStart
不会指向列表的开头。list1
列表中的第一项也不是。insert
是列表开头的对象。更换线
listStart = &list1;
经过
listStart = &insert;
清理建议
线
l = i;
在insertEntry
也没用。它在函数中不做任何事情。它都不会改变任何东西main
。去掉它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句