簡體   English   中英

為什么我不能在下面的程序中初始化指向變量的指針值

[英]why am i not able to initialize value of pointer to a variable in the below programme

#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。

輸出

實際上,您正在為b分配一個值,但是由於您更改了a的值,因此您不會注意到分配,假設您為a輸入4 ,為b輸入5

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);

暫無
暫無

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

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