初學者編寫計算圓周長的程序,編譯通過但運行直接崩潰:
#include <stdio.h>
int main() {
float a, r = 0;
printf("please enter the radius of a circle:");
scanf("%f", r); // 錯誤:缺少 & 取地址符
a = 2 * 3.1416 * r;
printf("The radius of the circle is:%f", a);
return 0;
}
scanf 需要變量的地址來存儲輸入值,r 是浮點數值而非地址,導致非法內存訪問。
scanf("%f", &r); // 加上 & 取地址符
所有 scanf 系列函數(%d, %f, %lf 等)讀取基本類型時,參數必須是變量地址。字符數組名本身就是地址,故 %s 不需加 &。