为什么我的交换函数中的 print 语句给出这样的输出?

问题描述 投票:0回答:1
#include <stdio.h>
void swap(int* x, int* y){
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
    printf("The value of x and y inside the function is x = %d and y = %d", x, y);
}
int main()
{
    int x = 2, y =3;
    swap(&x, &y);
    return 0;
}

输出: 函数内 x 和 y 的值为 x = 6422300 和 y = 6422296

为什么函数内部x的值为6422300,y的值为6422296?

#include <stdio.h>
void swap(int* x, int* y){
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
    printf("The value of x and y inside the function is x = %d and y = %d", x, y);
}
int main()
{
    int x = 2, y =3;
    swap(&x,&y);
    printf("\nThe value of x and y in the main is x = %d and y = %d", x, y);
    return 0;
}

输出: 函数内 x 和 y 的值为 x = 6422300 和 y = 6422296 主要的 x 和 y 的值是 x = 3 和 y = 2

我尝试在main中分别编写x和y的打印语句,然后它工作正常。但为什么它在函数内部不起作用?

c function pointers pass-by-reference swap
1个回答
0
投票

当您将指针而不是整数传递给

printf
时,您的代码调用了未定义的行为。
%d
正在期待
int
。您需要取消引用
x
y

void swap(int* x, int* y)
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
    printf("The value of x and y inside the function is x = %d and y = %d", *x, *y);
}
© www.soinside.com 2019 - 2024. All rights reserved.