这是我在堆栈上的第一个问题。
我在练习2中遇到了问题,第11章 - 指针,在Stephen Cochan撰写的“C编程(第三版)”一书中。
问题是: 编写一个名为insertEntry的函数,将新条目插入到链表中。让过程将指向要插入的列表条目的指针(本章中定义的struct entry类型)和指向列表中元素的指针作为参数,之后将插入新条目。
我的代码是:
#include <stdio.h>
struct entry
{
int value;
struct entry *next;
};
void insertEntry ( struct entry newEntry, struct entry EntryNo ){
newEntry.next = EntryNo.next;
EntryNo.next = &newEntry;
}
int main (){
struct entry n1, n2, n3, n4, newEntry;
struct entry *listPointer = &n1; // with this pointer we mark the start of the list
n1.value = 100;
n1.next = &n2;
n2.value = 200;
n2.next = &n3;
n3.value = 300;
n3.next = &n4;
n4.value = 400;
n4.next = (struct entry *) 0; // we pinpoint that n4 will be the last entry of our list
newEntry.value = 340;
printf("The list before adding a new entry:\n");
while ( listPointer != (struct entry*) 0 ){
printf("%i\n", listPointer->value );
listPointer = listPointer->next;
}
listPointer = &n1;
insertEntry ( newEntry, n3 );
printf("The list after adding a new entry:\n");
while ( listPointer != (struct entry*) 0 ){
printf("%i\n", listPointer->value );
listPointer = listPointer->next;
}
return 0;
}
输出是:
The list before adding a new entry:
100
200
300
400
The list after adding a new entry:
100
200
300
400
然而,当我编写如下所示的代码时,我得到了所需的输出(这是值300和400中的新条目。
#include <stdio.h>
struct entry
{
int value;
struct entry *next;
};
int main (){
struct entry n1, n2, n3, n4, newEntry;
struct entry *listPointer = &n1; // with this pointer we mark the start of the list
n1.value = 100;
n1.next = &n2;
n2.value = 200;
n2.next = &n3;
n3.value = 300;
n3.next = &n4;
n4.value = 400;
n4.next = (struct entry *) 0; // we pinpoint that n4 will be the last entry of our list
newEntry.value = 340;
printf("The list before adding a new entry:\n");
while ( listPointer != (struct entry*) 0 ){
printf("%i\n", listPointer->value );
listPointer = listPointer->next;
}
listPointer = &n1;
newEntry.next = n3.next;
n3.next = &newEntry;
printf("The list after adding a new entry:\n");
while ( listPointer != (struct entry*) 0 ){
printf("%i\n", listPointer->value );
listPointer = listPointer->next;
}
return 0;
}
输出是:
The list before adding a new entry:
100
200
300
400
The list after adding a new entry:
100
200
300
340
400
所以问题是第一个代码上的函数,类似于添加的条目的值没有注册(或者没有正确地从函数返回)。我不知道,因为我在这里很困惑。如果有人能帮助我,我将非常感激。提前谢谢。
答案 0 :(得分:3)
您需要将对象的地址传递给您的函数。函数原型将是:
void insertEntry ( struct entry *newEntry, struct entry *EntryNo )
调用该函数时,将地址传递为:
insertEntry ( &newEntry, &n3 );
另外,由于我们修改了函数以将指针作为参数,我们还需要在函数内做一些修改:
void insertEntry ( struct entry *newEntry, struct entry *EntryNo ){
(*newEntry).next = (*EntryNo).next;
(*EntryNo).next = newEntry;
}
答案 1 :(得分:1)
由于您将对象直接传递给函数,因此它适用于对象的副本而不是对象本身。为了直接处理对象,您需要传递对象的地址。