为什么我们不能用C按引用传递指针? [英] why can't we pass the pointer by reference in C?
问题描述
我学习C.我写code,当我遇到一个分段故障来创建一个链表。我发现,在<一个解决我的问题href=\"http://stackoverflow.com/questions/2293033/why-is-this-c-linked-list-program-giving-segmentation-fault\">this题。
我试图通过引用传递一个指针。该解决方案说,我们不能这样做。我们有一个指针传递给一个指针。该解决方案为我工作。
不过,我不明白为什么会这样。谁能告诉原因?
I am learning C. I was writing code to create a linked list when i came across a segmentation fault. I found a solution to my problem in this question. I was trying to pass a pointer by reference. The solution says that we can't do so. We have to pass a pointer to a pointer. This solution worked for me. However, I don't understand why is it so. Can anyone tell the reason?
推荐答案
从的 C程序设计语言 - 第二版的(K&安培; R 2):
From The C Programming Language - Second Edition (K&R 2):
5.2指针和函数参数
由于C按值传递函数的参数,也没有直接的方法
对被调用的功能,以改变在调用函数中的变量。
Since C passes arguments to functions by value, there is no direct way for the called function to alter a variable in the calling function.
...
指针参数使函数来访问和更改对象
调用它的功能。
Pointer arguments enable a function to access and change objects in the function that called it.
如果你明白:
void fn1(int x) {
x = 5; /* a in main is not affected */
}
void fn2(int *x) {
*x = 5; /* a in main is affected */
}
int main(void) {
int a;
fn1(a);
fn2(&a);
return 0;
}
出于同样的原因:
for the same reason:
void fn1(element *x) {
x = malloc(sizeof(element)); /* a in main is not affected */
}
void fn2(element **x) {
*x = malloc(sizeof(element)); /* a in main is affected */
}
int main(void) {
element *a;
fn1(a);
fn2(&a);
return 0;
}
正如你所看到的,有一个与 INT
和一个指向元素没有什么区别,你需要一个指针传递给 INT
,在第二个你需要传递一个指针的指针的元素。
As you can see, there is no difference between an int
and a pointer to element, in the first example you need to pass a pointer to int
, in the second one you need to pass a pointer to pointer to element.
这篇关于为什么我们不能用C按引用传递指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!