簡體   English   中英

為什么我的 output 是 5 和 0 而不是 6 和 5,請幫幫我

[英]Why is my output 5 and 0 instead of 6 and 5, please help me

為什么我的代碼 output 是 5 和 0,而不是 6 和 5。我想我應該得到 6 和 5。我是新人。請幫助我。

#include <stdio.h>
int swap(int a,int b);
int main()
{   int x =5;
    int y =6;
    printf("%d %d\n",x,y);
    int number[2]={swap(x,y)};
    x=number[0];
    y=number[1];
    
    printf("%d %d\n",x,y);
    return 0;
}
int swap(int a,int b)
{
    return b,a;
}

這里有幾件事是錯誤的。

首先,您不能在 C 中返回多個值,就像在 Python 中一樣。 return b, a; 使用逗號運算符,它計算其兩個操作數並返回第二個。 所以這相當於只return a; .

其次,您的數組初始化程序僅初始化數組的第一個元素。 初始化大括號中只有一個表達式,因此初始化number[0] 數組的其余元素默認初始化為0

結合這兩者,它相當於:

int number[2] = {y, 0};

我可以看到您是 C 編程的新手。 問題出在您的swap() function 中。 您正在使用 C 中不存在的語言結構,即元組。 查看指針,了解從 function 返回多個值的正確方法。

此 function...

 int swap(int a,int b)

...返回一個int ,正如它的原型所說。

這個說法...

 return b,a;

... 涉及 C 的逗號運算符, ,它計算其左側操作數,丟棄結果,然后計算其右側操作數的值。 由於評估b在您的情況下沒有副作用,因此該return語句等效於

return a;

在 C 中,使用少於數組長度的顯式元素來初始化數組是有效的。 對於像您這樣的自動(本地,非static )數組,只要至少一個元素是初始化器,所有未顯式初始化的元素都會被隱式初始化(在int元素的情況下為 0)。 因此,對於您的swap()實施,這...

 int number[2]={swap(x,y)};

... 相當於

    int number[2] = { x, 0 };

,其中解釋了 output。

這是解決您的問題的方法。

#include <stdio.h>

void swap(int *a,int *b);

int main()
{
    int x = 5;
    int y = 6;
    swap(&x, &y);
    printf("post swap x = %d, y =  %d\n", x, y);
    return 0;
}

// No need to return anything, we change the x, y values using the pointer
// This is passing by reference. Instead of passing the value, we are
// passing the reference (i.e address of the variable). swap function can
// now directly access the values and change them
void swap(int *a, int *b)
{
    int tmp;
    printf("Swap got a = %d, b = %d\n", *a, *b);   // Note: we access value of a pointer using * in front of the pointer varaible
    tmp = *a;
    *a = *b;
    *b = tmp;
}

輸出:

bhakta: /tmp$ cc x.c
bhakta: /tmp$ ./a.out
Swap got a = 5, b = 6
post swap x = 6, y =  5

暫無
暫無

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

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