我是 C 編程的新手。決定通過做一些 cs50 開放課件中的問題集來學習。以下代碼會產生分段錯誤(核心轉儲)錯誤。我不明白為什么。我讀過一個分段錯誤與訪問您無權訪問的記憶體有關。我不明白是什么導致了這種情況。我假設它與指標有關。我是指標的新手。謝謝你。
#include <stdio.h>
// https://cs50.harvard.edu/x/2021/labs/1/population/
float yearly_llamas(float starting_population) {
// returns number of llamas at the end of the year
float born = starting_population / 3;
float died = starting_population / 4;
float end_of_year_pop = starting_population born - died;
return end_of_year_pop;
}
int main(void) {
// use floats for precision
float *start_population;
float *end_population;
// set start lower limit
int start_min = 9;
// make sure input for starting population is greater than or equal to 9
do {
printf("Starting population: ");
scanf("%f", start_population);
} while (*start_population < start_min);
// get ending population, make sure greater than or equal to the starting population
do {
printf("Ending population: ");
scanf("%f", end_population);
} while (*end_population < *start_population);
// print for verification
printf("%f\n", *start_population);
printf("%f\n", *end_population);
float end_pop = yearly_llamas(*start_population);
printf("Llamas at the end of the year: %f\n", end_pop);
return 0;
}
uj5u.com熱心網友回復:
您宣告了一個指向 float 的指標,但該指標沒有指向任何內容,因為您沒有為其分配地址。
更改這些行
float *start_population;
float *end_population;
到
float f_start_population;
float f_end_population;
float *start_population = &f_start_population;
float *end_population = &f_end_population;
應該解決分段錯誤。
uj5u.com熱心網友回復:
當另一個答案告訴您解決方案時,我想強調查找(和解決)此類問題的方法:使用除錯器。它是程式員的一個重要工具,最好是盡早學會使用它。在這種情況下,您的問題很簡單,可以通過任何除錯器輕松找到。稍后,當您將使用更復雜的代碼和多執行緒時,在嘗試解決您的(復雜)問題時很難學會使用它。請嘗試使用除錯器自行解決此問題。
如果您使用的是 Linux,則可以使用gdb并運行代碼直到它崩潰。然后,您檢查回溯 ( bt) 以查看最后執行的行。最后,您在崩潰的前一行中定義了一個斷點(p #n其中#n是行號),然后檢查值(p $variable使用$variable變數的名稱)并嘗試查看為什么它不起作用。
使用 GUI 除錯器,它應該更容易(例如使用 Visual Studio 或 Code::blocks)。
uj5u.com熱心網友回復:
當你像這樣宣告一個指標變數 f 時,float *f;你只能“使用”它,如果指標實際上指向你保留的記憶體(術語已分配)。您可以使用該malloc()函式在“堆”上分配變數,或者更簡單地通過撰寫float my_float;和使用在堆疊上創建一個單獨的變數(稱為自動變數)。所以你得到:
float my_startfloat;
float *start_population = &my_startfloat;
也就是說,我只會宣告一個浮點數(第一行),然后在適當的情況下使用它的地址:&my_startfloat。例如:
float my_startfloat;
scanf("%f", &my_startfloat);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/364671.html
