我想知道是否可以在我的程序上获得一些帮助。如标题所述,我的程序出现访问冲突。我意识到它与取消引用垃圾指针有关,而且我很确定我已经缩小了它中断的范围,我只是不确定它为什么会中断,以及如何修复它。代码如下:
void determineInputType(char input[kMaxUserInput])
{
char* flag = NULL;
if (*(flag = strchr(input, '.')) != NULL)
{
double grade = 0;
if ((sscanf(input, "%lf", grade)) == 1) // problem is on this line
{
//rest of the code continues here
我是如何获得输入的:
void getUserInput(char* userInput)
{
printf("Enter a student's grade: ");
fgets(userInput, kMaxUserInput, stdin);
clearCRLF(userInput);
}
最后是主要内容:
int main(void)
{
char userInput[kMaxUserInput] = { 0 };
getUserInput(userInput);
determineInputType(userInput);
return 0;
}
任何对此的帮助将不胜感激,因为它已经困扰了我一段时间。非常感谢您抽出时间,如果我还需要发布任何其他内容,请告诉我。
最佳答案
scanf
系列要求您提供一个指向您想要填充的值的指针:
if ((sscanf(input, "%lf", &grade)) == 1) // problem is no longer on this line
按照您的方式,将 grade
设置为零,然后使用 that 作为指针。
标准的相关部分(C++11 遵循的 C99)是 7.19.6.2/12
(我的粗体):
a,e,f,g
- Matches an optionally signed floating-point number, infinity, orNaN
, whose format is the same as expected for the subject sequence of thestrtod
function. The corresponding argument shall be a pointer to floating.
l
(ell) - Specifies that ... a followinga
,A
,e
,E
,f
,F
,g
, orG
conversion specifier applies to an argument with type pointer to double; ...
关于C++: 0xC0000005: 访问冲突写入位置 0x00000000,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27955497/