c - 当函数中的值发生变化时,指针不反射(reflect)变化

标签 c pass-by-reference

我正在使用数组实现链表。它有一个函数 Reverse 定义如下

void Reverse(List *l)
{
    List *m=CreateList(ListSize(l));
    for(int i=0;i<l->count;i++)
    {
        m->array[i]=l->array[l->count-i-1];
        m->count++;
    }
    free(l->array);
    free(l);
    l=m;
    //Traverse(l); Here it prints the reversed List

}

它以一个列表结构作为参数。我像这样从 main 调用它

int main()
{
    size=5;
    List *l=CreateList(size);
    Reverse(l);
    Traverse(l); //Here the list is not printing the reversed list !

}

为什么我对 l 所做的反向更改没有显示在 main() 中? 谢谢!

最佳答案

你必须传递一个双指针才能改变指针指向的位置。

void Reverse(List **l);
Reverse(&l);

在 C 中不可能通过引用传递,来自 www-cs-students.stanford.edu :

In C, Pass-by-reference is simulated by passing the address of a variable (a pointer) and dereferencing that address within the function to read or write the actual variable. This will be referred to as "C style pass-by-reference."

关于c - 当函数中的值发生变化时,指针不反射(reflect)变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45849878/

相关文章:

c++ - 使用 initializer_list 上的数据

c# - 跨线程使用引用对象

javascript - 在 JavaScript 中通过引用传递变量

C 递归函数回文

c - 将小数转换为分数表达式的算法

c - gRegex 不解析“字符

c - Ncurses 读取小键盘键和转义

c - 如何以正确的方式转换 void** 指针?

javascript - array1.concat(array2) 在函数调用后不持久的影响

php - 递归和引用传递