C - 通过引用传递?

时间:2017-09-02 16:51:11

标签: c pointers

我来自一个占主导地位的面向对象的编程语言,并试图更多地理解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

4 个答案:

答案 0 :(得分:2)

看看这个:Passing by reference in C

在您的示例中,您传递的是变量的值,您希望传递指针的值。

答案 1 :(得分:1)

将它们作为指针传递。如果你没有返回值 - 声明函数void,或返回一些东西

<div id="dropDownDiv">
        <select id="opt1">
            <option value=1>Option 1</option>
            <option value=2>Option 2</option>
            <option value=3>Option 3</option>
        </select><select id="opt2">
            <option value=1>Option 1</option>
            <option value=2>Option 2</option>
            <option value=3>Option 3</option>
        </select>
    </div>

并在主

void doStuff(int *v)
{
    *v = *v + 10; // main->value = 10
}

void otherStuff(int *v)
{
    *v = *v - 10; // main->value = 0
}
函数中的

int * v意味着v是指向int对象的指针。 在函数call&amp; value中将指针(地址)传递给值。 在函数中取消引用指针v - 所有的值都是在值上完成的。

答案 2 :(得分:0)

您应该将指针传递给函数的整数而不是整数本身。

对于你接受一个整数指针(引用)而不是整数本身的函数,它应该像这样声明:

int doStuff(int *v)

此处*表示将传递指向整数的指针。

然后在函数本身中,我们必须将指向derefernece的整数本身:

int doStuff(int *v)
{
    // The * here is dereferncing the pointer to the integer it is pointing to
    *v = *v + 10; // main->value = 10
}

最后,应修改主例程以传递指向value的指针,而不是使用&符号来表示自身:

dostuff(&value);

答案 3 :(得分:-1)

在您的情况下,您必须从函数返回一个值:

int doStuff(int v)
{
v = v + 10; // main->value = 10

return v;

}

int otherStuff(int v)
{
v = v - 10; // main->value = 0
return v;
}    

在main中你必须保存函数返回的值 value=doStuff(value);