我是个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;
}发布于 2021-11-24 08:35:59
你声明了一个浮点型的指针,但是这个指针没有指向任何东西,因为你没有给它分配地址。
更改这些行
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;应该解决分段故障。
发布于 2021-11-24 08:58:20
虽然另一个答案告诉您解决方案,但我想强调查找(和解决)这类问题的方法:使用调试器。它是程序员的一个重要工具,最好尽快学会使用它。在这种情况下,您的问题非常简单,任何调试器都很容易发现。稍后,当您要处理更复杂的代码和多线程时,当您尝试解决(复杂)问题时,将很难学会使用它。请尝试使用调试器自行解决此问题。
如果您使用的是Linux,您可以使用gdb并运行代码,直到它崩溃。然后,检查回溯(bt)以查看最后执行的行。最后,在崩溃的前一行中定义一个断点(p #n,其中#n是行号),并检查这些值(使用$variable作为变量名的p $variable),并尝试了解它不工作的原因。
使用GUI调试器,应该更容易(例如,使用Visual Studio或Code::blocks)。
发布于 2021-11-24 09:08:03
当你像这样声明一个指针变量f时,你只能“使用”它,如果指针是,实际上是,指向你保留的内存(这个术语是分配的)。您可以使用malloc()函数在“堆”上分配变量,或者更简单地,通过编写float my_float;并使用它在堆栈上创建一个单独的变量(称为自动变量)。所以你会得到:
float my_startfloat;
float *start_population = &my_startfloat;也就是说,我只声明了一个浮动(第一个)行,然后在适当的地方使用它的地址:&my_startfloat。例如:
float my_startfloat;
scanf("%f", &my_startfloat);https://stackoverflow.com/questions/70090955
复制相似问题