0

我有这个功能:

void update(int something, int nothing) {
    something = something+4;
    nothing = 3;
}

然后函数调用:

int something = 2;
int nothing = 2;

update(something, nothing);

在函数内部,有些东西是 6,没有东西是 3,但是因为我们不返回任何东西,所以值不会改变。

对于一个值,我可以使用函数的返回值,但现在我认为我必须使用指针,对吧?

我希望从函数返回的东西和无,所以我可以在函数调用后使用新值,我该怎么做?:)

4

3 回答 3

8

使用发送值&并使用接收它们*

例子:

void update(int* something, int* nothing) {
    *something = *something+4;
    *nothing = 3;
}

int something = 2;
int nothing = 2;

update(&something, &nothing);

两年没有使用C,但我认为这是正确的。

于 2013-09-17T06:56:31.860 回答
1

使用打击代码:

1)

  void update(int * something, int * nothing) 
    {
        *something = *something + 4;
        *nothing = 3;
    }

    int something = 2;
    int nothing   = 2;

    update(&something, &nothing);

这意味着您将变量的地址传递给函数更新,并更改地址内的值。

或者

2) 做一些东西,没有全局变量。这也应该有效。但这不是一个好的解决方案。

于 2013-09-17T07:01:40.410 回答
1

您要做的是引用和取消引用变量。通过调用&variable您获取指向该变量的指针,通过调用*variable您获取该变量指向的内容。在这里,您可以获得有关指针的更多信息。

void update(int* something, int* nothing) {
    *something = *something+4
    *nothing = 3
}

int something = 2;
int nothing = 2;

update(&something, &nothing);

这是你想要的,但它不是最好的风格,因为不知道代码的人无法理解你在做什么。我的意思是,你不应该修改参数变量,只要它不是真正需要的。大多数函数都可以在没有这种行为的情况下编写。

如果你真的需要“返回”两个变量,我会这样做:

int update(int something, int* nothing) {
    something += 4;
    *nothing = 3;
    return something;
}

int something = 2;
int nothing = 2;

something = update(something, &nothing);
于 2013-09-17T06:58:19.040 回答