所以我们最近在课堂上学到了列表,我想练习一下。程序不能运行。我填充节点失败了吗?我太头晕了,无法集中精力寻找丢失的钥匙。很抱歉发了这么琐碎的帖子!
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int val;
struct node *next;
}node_t;
node_t* create_node(int value,node_t *nextnode) {
node_t *newnode=(node_t*)malloc(sizeof(node_t));
if(newnode==NULL) {
printf("ERROR ALLOCATING");
exit(0);
}
newnode->val=value;
newnode->next=nextnode;
return newnode;
}
void fill_list(node_t *head) {
int i=1;
node_t *current;
for(;i<21;i++) {
current=create_node(i,head);
head=current;
}
}
void print_list(node_t *head) {
node_t *current=head;
while(current) {
printf("%d",current->val);
current=current->next;
}
}
int main() {
node_t *head=NULL;
fill_list(head);
print_list(head);
return 0;
}发布于 2020-02-18 21:59:38
你的问题是fill_list永远不会返回新的头部。因此,main中的head仍然是NULL。
改变这种行为的一种简单方法是让fill_list返回新的头部:
node_t* fill_list(node_t *head) {
int i=1;
node_t *current;
for(;i<21;i++) {
current=create_node(i,head);
head=current;
}
return head;
}发布于 2020-02-18 22:08:23
在函数fill_list中,参数head正在更改。
void fill_list(node_t *head) {
int i=1;
node_t *current;
for(;i<21;i++) {
current=create_node(i,head);
head=current;
}
}但是该函数处理传递给该函数的参数的副本。因此,在main中定义的原始指针头对这些更改一无所知。
您必须从函数返回函数的参数头部的值,并将其赋值给main中定义的指针头部。
所以这个函数看起来像这样
node_t * fill_list(node_t *head) {
for( int i = 1; i < 21; i++ )
{
head = create_node( i, head );
}
return head;
}在main中必须有
node_t *head = NULL;
head = fill_list( head );另一种方法是通过引用将指针头传递给函数fill_list。在这种情况下,函数可以看起来
void fill_list( node_t **head ) {
for ( int i = 1; i < 21; i++ ) {
*head = create_node( i, *head );
}
}在main中,你应该写下
node_t *head = NULL;
fill_list( &head );发布于 2020-02-18 22:23:18
Problem
C中的函数参数是“按值传递”。这样做的问题是,您的fill_list函数需要一个指向名为head的node_t的指针,但是您对该指针所做的任何更改都不会影响该函数外部的head的值。函数中的head与main()中的head完全不同。
快速修复
如果您确实想要更改head (函数外部的值)的值,那么您必须向函数传递一个指向head所在的内存位的指针。对于您的示例,这意味着指向node_t的指针。
因此,您的fill_list将如下所示:
void fill_list(node_t **head) {
int i=1;
node_t *current;
for(;i<21;i++) {
current=create_node(i, *head);
*head=current;
}
}请注意,您现在必须在将指针传递给create_node之前取消对它的引用。
通过在赋值*head = current中取消引用,可以设置head指向的内存的内容。它与保存main()中声明的head变量的内存相同。这就是你想要的。
现在您可以像这样调用fill_list:
fill_list(&head)
更好地修复了
让fill_list返回一个指向头部的指针,例如:
node_t* fill_list() {
int i=1;
node_t *head = NULL;
node_t *current;
for(;i<21;i++) {
current=create_node(i, head);
head=current;
}
return head;
}然后是main()
int main() {
node_t *head = fill_list();
print_list(head);
return 0;
}https://stackoverflow.com/questions/60282552
复制相似问题