为什么第一个代码可以工作并交换变量,而第二个代码却不能,我只是尝试在不使用函数的情况下做同样的事情

问题描述 投票:0回答:1

这是第一个代码

#include<stdio.h>
#include<conio.h>
void swap(int *a,int *b){
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main()
{
    int x=10,y=20;
    printf("Before swap x = %d and y = %d\n",x,y);
    swap(&x,&y);
    printf("After swap x = %d and y = %d",x,y);
    return 0;
}

这是第二个

#include<stdio.h>
#include<conio.h>
int main()
{
    int x=10,y=20;
    printf("Before swap x = %d and y = %d\n",x,y);
    int *a = &a;
    int *b = &b;
    int temp = *a;
    *a = *b;
    *b = temp;
    printf("After swap x = %d and y = %d",x,y);
    return 0;
}

我尝试使用指针交换 x 和 y 的值,在第一个代码中我使用了一个函数,在第二个代码中我尝试做同样的事情但没有使用函数,第一个代码有效,但第二个代码没有。

c
1个回答
0
投票

在第一个示例中,您获取

x
的地址并将其作为参数传递给
swap()
函数。

在第二个示例中,您使用

a
的地址!是的,这是 C 的一个奇怪的特性:您可以在其初始赋值中使用变量:

int * a = &a;  // takes the address of `a` and assigns it to `a`

如果您调高编译器警告,它会向您抱怨您正在将

int **
分配给
int *

你的意思是获取

x
的地址,就像你的第一个例子一样:

int * a = &x;

确保打开警告:

  • GCC 和 Clang:
    -Wall -Wextra
  • MSVC:
    /W3

编译代码时,找出最上面的错误或警告,修复它,并继续这样做,直到可以编译而不生成任何警告或错误。

学习 C 语言编程有点艰难,但这是值得的!

© www.soinside.com 2019 - 2024. All rights reserved.