簡體   English   中英

C函數,使用指針代替返回

[英]C function, use pointer instead of return

我有這個功能:

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

然后函數調用:

int something = 2;
int nothing = 2;

update(something, nothing);

在函數內部,值為6,什么都不為3,但是由於我們不返回任何值,因此值不會更改。

對於一個值,我可以使用函數的返回值,但是現在我認為我必須使用指針,對嗎?

我想從函數中返回東西,所以我可以在函數調用后使用新值,該怎么做? :)

使用&發送值&並使用*接收值

例:

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

int something = 2;
int nothing = 2;

update(&something, &nothing);

兩年沒有使用C,但是我認為這是正確的。

您要做的是引用和取消引用變量。 通過調用&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);

使用打擊代碼:

1)

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

    int something = 2;
    int nothing   = 2;

    update(&something, &nothing);

這意味着您要將變量的地址傳遞給函數update,並更改地址內部的值。

要么

2)兩者都做,什么都不做全局變量。 那也應該起作用。 但這不是一個好的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM