简体   繁体   English

C函数,使用指针代替返回

[英]C function, use pointer instead of return

I have this function: 我有这个功能:

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

And then the function call: 然后函数调用:

int something = 2;
int nothing = 2;

update(something, nothing);

Inside the function, something would be 6 and nothing would be 3, but because we do not return anything, the values does not change. 在函数内部,值为6,什么都不为3,但是由于我们不返回任何值,因此值不会更改。

For just one value, I could use the return-value from the function, but now I think that I have to use pointers, right? 对于一个值,我可以使用函数的返回值,但是现在我认为我必须使用指针,对吗?

I want both the something and the nothing to be returned from the function so I could use the new values after the function call, how do I do that? 我想从函数中返回东西,所以我可以在函数调用后使用新值,该怎么做? :) :)

Send values using & and receive them using * 使用&发送值&并使用*接收值

Example: 例:

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

int something = 2;
int nothing = 2;

update(&something, &nothing);

Two years without using C, but I think this is correct. 两年没有使用C,但是我认为这是正确的。

What you want to do is referencing and dereferencing the variables. 您要做的是引用和取消引用变量。 By calling &variable you get the pointer to that variable, by calling *variable you get, what this variable points to. 通过调用&variable您将获得指向该变量的指针,通过调用*variable您将获得此变量指向的对象。 Here you can get more information about pointers. 在这里,您可以获得有关指针的更多信息。

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

int something = 2;
int nothing = 2;

update(&something, &nothing);

this is what you want, but it isn't the best style, as people that don't know the code could not understand what you are doing. 这就是您想要的,但这不是最好的样式,因为不了解代码的人无法理解您在做什么。 What I mean by that is, that you should not modify parameter variables as long as it is not really needed. 我的意思是,只要确实不需要,就不要修改参数变量。 Most functions can be written without such behaviour. 大多数函数可以在没有这种行为的情况下编写。

If you really need to "return" two variables, this is what I would do: 如果您确实需要“返回”两个变量,这就是我要做的:

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

int something = 2;
int nothing = 2;

something = update(something, &nothing);

Use the blow Code: 使用打击代码:

1) 1)

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

    int something = 2;
    int nothing   = 2;

    update(&something, &nothing);

It means you are passing the address of the variable into function update, and changing the value inside the address. 这意味着您要将变量的地址传递给函数update,并更改地址内部的值。

OR 要么

2) make both something, nothing global variable. 2)两者都做,什么都不做全局变量。 That also should work. 那也应该起作用。 But it is not a good solution. 但这不是一个好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM