繁体   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