[英]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.