我是C語言的初學者。我正在自己練習幾個代碼,同時我遇到了這個演算法。下面是代碼。
#include <stdio.h>
int main() {
int a = 1;
printf("value of a = %d\n", a);
printf("address of a = %u\n", &a);
int *p;
printf("value of p = %d\n", p);
p = 2;
printf("value of p = %d\n", p);
a = a p;
printf("value of addition =%d\n", a);
return 0;
}
**OUTPUT**
value of a = 1
address of a = 947268620
value of p = 947268880
value of p = 2
value of addition =6
為什么我得到 6 而不是 3,結果有什么我遺漏的嗎
uj5u.com熱心網友回復:
因為您沒有將 p 指向的地址的值設定為 2,所以您將變數 int *p 分配/指向記憶體中的值 2,這不是您應該訪問的記憶體。相反,您需要將 p 指向您可以訪問的記憶體(變數或動態分配的記憶體)并取消參考*p = 2訪問 p 指向的值的指標。您的代碼應該看起來像這樣
int a = 1;
printf("value of a = %d\n", a);
printf("address of a = %u\n", &a);
int _p = 0;
int *p = &_p;
printf("value of p = %d\n", *p);
*p = 2;
printf("value of p = %d\n", *p);
a = a *p;
printf("value of addition =%d\n", a);
uj5u.com熱心網友回復:
一個人必須“走過”關于該代碼的編譯器警告。
下面是相同的代碼,帶有強制轉換以使一些警告靜音。額外的計算和列印陳述句應該清楚地表明編譯器如何以不同的方式處理指標值(記憶體地址)和整數值。
#include <stdio.h>
int main() {
int a = 1;
printf("value of a = %d\n", a);
printf("address of a = %u\n", &a); // incorrect format spec for printing address
int *p;
printf("value of p = %d\n", p); // uninitialised and undefined behaviour
p = (int*)2; // coercive casting integer to pointer-to-integer
printf("value of p = %d\n", p); // incorrect format spec for a memory address
a = (int)(a p); // coercive casting address to integer
printf("value of addition =%d\n", a);
// ADDED these statements
a = 1; // restore value of a
a = a (int)p; // coercive casting address to integer
printf("value of addition =%d\n", a);
return 0;
}
value of a = 1
address of a = 1703728
value of p = 1
value of p = 2
value of addition =6
value of addition =3 <== was this the expected result?
C 將盡力使用顯式程式陳述句。
“垃圾進垃圾出。”
撰寫正確的代碼,而不是“可愛”的代碼。
uj5u.com熱心網友回復:
感謝您的回復。有幫助。我得到了我需要的輸出。但我需要知道的是,a = a p; 行的邏輯是什么?在我的代碼中給出了 6。
正如你所說,我將 2 作為地址分配給 p(即 p = 0x2)。因此,當加法發生時 a = 1 和 p = 0x2 有一個我們不知道的隨機值,這是因為我沒有將特定地址分配給指標變數 p。結果是 6 我是對的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/511266.html
標籤:C指针变量
上一篇:如何更新鍵是變數的字典?
下一篇:如何使用變數格式化文本?
