【问题标题】:why am i not able to initialize value of pointer to a variable in the below programme为什么我无法在下面的程序中初始化指向变量的指针值
【发布时间】:2021-10-24 06:11:09
【问题描述】:
#include<Stdio.h>

int main()
{
    int a ,b;
    int *p;
    int *q;
    printf("enter the value of a and b");
    scanf("%d%d",&a,&b);
    p = &a;
    q = &b;
    printf("value of a and b is %d and %d",a,b);
    a = *q;
    b = *p;
    printf("value of a and b is %d and %d",a,b);
}

我无法更改 b 的值,即使将其重新定义为指针 p。

output

【问题讨论】:

    标签: c pointers swap


    【解决方案1】:

    您实际上是在为b 赋值,但由于您更改了a 的值,因此您不会注意到该赋值,假设您输入4 为a 和5对于b:

    a = *q;  // q points at b, which is 5, so a = 5
    b = *p;  // p points at a, which is now 5, so, b = 5
    

    要交换值,您可以这样做:

    int tmp = a; // store the value of a, 4
    a = b;       // assign, a = 5
    b = tmp;     // assign, b = 4 (the stored value)
    

    或者用它做一个函数:

    void swap(int *lhs, int *rhs) {
        int tmp = *lhs;
        *lhs = *rhs;
        *rhs = tmp;
    }
    

    然后调用它:

    swap(&a, &b);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 2012-08-23
      • 2013-04-01
      • 1970-01-01
      相关资源
      最近更新 更多