我来自一种占主导地位的面向对象的编程语言,试图进一步了解C的功能,因此决定制作一个小程序来实现这一点。
我遇到的问题是使用DI通常可以解决的问题,如何将值的引用传递给另一个函数,以便它可以在不使用全局变量的情况下对其执行算术运算?
考虑以下程序:
#include <stdio.h>
#include <stdlib.h>
int doStuff(int v)
{
v = v + 10; // main->value = 10
}
int otherStuff(int v)
{
v = v - 10; // main->value = 0
}
int main()
{
int value = 0;
int stop = 0;
do
{
printf(" %i should be 0 \n", value);
doStuff(value); // "value" = 10
printf(" %i should be 10 \n", value);
otherStuff(value); // "value" = 0
printf(" %i should be 0 \n", value);
exit(0);
if(value >= 10)
{
stop = 1;
}
} while(!stop);
}
输出:
0 should be 0
0 should be 10
0 should be 0
将它们作为指针传递。如果不返回值,则将函数声明为void或返回某些内容
void doStuff(int *v)
{
*v = *v + 10; // main->value = 10
}
void otherStuff(int *v)
{
*v = *v - 10; // main->value = 0
}
并在主要
doStuff(&value); // "value" = 10
/*....*/
otherStuff(&value); // "value" = 0
函数中的int * v表示v是指向int对象的指针。在函数调用&value中,将指针(地址)传递给该值。在函数中取消对指针v的引用-所有插入实际上都是对该值进行的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句