【发布时间】:2022-01-02 12:57:58
【问题描述】:
我是 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;
}
【问题讨论】:
-
现在是学习调试的好时机。在调试器中运行您的程序,它会将您指向触发 seg 错误的确切代码行。也可以使用调试器来跟踪/检查代码流和变量值。
-
float *start_population;声明了一个未初始化的指针。scanf("%f", start_population);尝试读取数据并将其写入该指针。这个故事的寓意是不要使用指针,如果你不需要,但如果你确保它们指向有效的内存。在你的情况下使用float sp; scanf("%f", &sp); -
float *start_population; scanf("%f", start_population);这是行不通的,因为start_population是一个未初始化的指针。试试float start_population; scanf("%f", &start_population);
标签: c pointers segmentation-fault cs50