为什么我定制的CVI函数似乎无法改变它的参数的值?



主要软件: LabWindows/CVI Development Systems>>LabWindows/CVI Full Development System
主要软件版本: 7.1
主要软件修正版本: N/A
次要软件: N/A

问题: 我定制的CVI函数似乎只能临时的改变它的参数的值。通过变量窗口(在debug模式下,对代码进行步调),我发现在函数内部,值发生改变了,但一旦退出函数,参数就还原为在函数调用之前的值。为什么会这样?

解答: 这实际上是C语言的问题而不是CVI本身。多数情况下是因为你通过值来传递你的参数而不是通过引用。当你用值来传递一个参数,一个数据的拷贝会被产生并传递给函数。一旦函数运行完毕,拷贝数据对应的内存区域将被释放或重新分配,在函数内部,对该参数任何你所认为的修改都将随之丢失。

如果你希望即使函数运行结束了,函数内部对参数所做的修改仍被保留,那你必须用引用来传递参数。这意味着你需要传递给函数的是待修改数据的地址而非数据的拷贝,这样你的函数将可以直接修改数据本身。

如下所示的代码给出了怎样通过值和引用来传递一个参数。代码的输出(如下面的附件所示)证明了一个通过引用来传递的参数是怎样与在函数中所修改的值保持一致的。相对的,通过值来传递的参数是不会改变的。
#include <stdio.h>

void foo(int bach); //does not alter the variable--passing parameter by value
void foo2(int *bach); //does alter the variable--passing parameter by reference

void main() {
int js=0;
printf("\n(from main) before calling foo, js=%d\n",js);
foo(js);
printf("\n(from main) after calling foo, js=%d",js);
foo2(&js);
printf("\n(from main) after calling foo2, js=%d",js);
getc(stdin);
}

void foo(int bach) {
printf("\nI, the function foo, will add 50 to the
variable js,\n even though I only have a copy
of the variable.");
bach=bach+50;
}

void foo2(int *bach) {
printf("\nI, the function foo2, will modify the original
variable instead (using pointer),\n so that the change
is reflected in main, even after the function has ended.");
*bach=*bach+99;
}
欲了解更多关于指针的内容,最好的着陆点是如以下链接所示的一本'C'语言的参考书,尽管还有其他很多好的基础的书是关于这个主题的。链接如下:

相关链接: KnowledgeBase 0ZD9LMTL: What Are the Different Areas of Memory and What Is Their Scope?
The C Programming Language, Second Edition by Brian W. Kernighan and Dennis M. Ritchie

附件:







报告日期: 11/15/2006
最近更新: 11/21/2006
文档编号: 27AFC35T