自从我开始使用C
学习数据结构以来的一两个月里,我一直在遵循一种编写链表的特定方法。看起来像这样。
#include<stdio.h>
#include<stdlib.h>
struct Node{
int exponent;
int coeff;
struct Node *next;
};
typedef struct Node N;
N *st = NULL;
void insert(N *node, int c, int e){
N *temp;
node->exponent = e;
node->coeff = c;
if(st == NULL){
node->next = st;
st = node;
} else {
temp = st;
while(temp->next != NULL){
temp = temp->next;
}
node->next = temp->next;
temp->next = node;
}
printf(" %p", st); //this is written on purpose, not that i write it everytime
}
我从主方法中调用它,
N *node = malloc(sizeof *node);
insert(node, 1, 2);
四个这样的调用的 printf 的输出是
00340D18 00340D18 00340D18 00340D18
即起始指针的值保持不变,但如果我在代码中做一些小的改变
typedef struct Node N;
void insert(N *node, N *st, int c, int e){
N *temp;
node->exponent = e;
node->coeff = c;
if(st == NULL){
node->next = st;
st = node;
} else {
temp = st;
while(temp->next != NULL){
temp = temp->next;
}
node->next = temp->next;
temp->next = node;
}
printf(" %p", st);
}
并在main方法中声明起始指针
N *strt = NULL;
node = malloc(sizeof *node);
insert(node, strt, 1, 1);
然后像前面的情况一样运行四次,开始指针的值会改变
每次通话后
00560D18 00560D30 00560D48 00560D60
为什么会发生这种情况? 如果我想将起始指针作为参数传递,应该进行哪些更改?
最佳答案
Why does this happen?
发生这种情况是因为对 st
的更改对于调用者来说是不可见的。也就是说,st = node
对调用者没有任何影响。函数更改了自己的副本,并且在函数返回后,如果调用者打印 strt
,它仍然是 NULL
。
这是一个有点微妙的结果,因为在 C 语言中参数是按值传递的,甚至是指针。因此,您按值传递 strt
。您可以更改 st->whatever
,因为它是一个指针,更改将传播到调用者,但更改 strt
本身不起作用。
And if i want to pass the start pointer as a parameter what changes should be made
这是该网站上的常见问题,还有一个 C FAQ这描述了问题。您可以做的一个简单但有些麻烦的更改是让该函数采用
N **st
并传递 &strt
。
关于c - 理解c中两个链表实现之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22267883/