尝试将浮点数读入数组时,scanf崩溃 [英] scanf crashes when trying to read a float into an array

查看:99
本文介绍了尝试将浮点数读入数组时,scanf崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

 双倍值[8],累计[8]; 

printf(输入第一个十进制数字:);
scanf(%f,values [0]);
printf( values [0] =%g,values [0]);

我的问题是scanf语句使程序崩溃,并且第二个printf从未执行。我最初的尝试是用双精度填充数组的每个插槽,但是由于这种方法不起作用,因此我将程序简化为这种方法,但这也不起作用。



<我是学习C的初学者,所以我可能犯了一个愚蠢的错误,我看不见。谢谢您的帮助!



编辑:



好的,所以显然,我需要在scanf语句中添加一个&符。但是我认为数组只是指向数组第一个元素的指针?为什么我必须使用&符号?

解决方案

scanf(%f,values [0 ]); -这里第一个元素的地址应该传递给scanf。您正在传递第一个元素的值,该值是垃圾值,因此它崩溃了。



values [0] *(值+ 0),因此这将给出第一个元素的值而不是第一个元素的地址。



执行 scanf(%lf,& values [0]); scanf(%lf,(values + 0) ); scanf(%lf,values);



double 使用%lf 而不是%f



程序中的另一个问题是未初始化的变量。声明时,尝试将变量初始化为零。

 双值[8] = {0}; 
double double [8] = {0};

如果代码初始化为零,则在代码的某些位置输入错误的指针将导致100%崩溃。否则,它将尝试访问一些垃圾值指针,这将导致内存损坏,这有时不会崩溃,而是会产生意外的输出。但这也有50%的机会导致崩溃,而您现在正在崩溃。


This is my code:

double values[8], cumulative[8];

printf("Enter first decimal number: ");
scanf("%f", values[0]);
printf("values[0] = %g", values[0]);

My problem is that the scanf statement crashes the program, and the second printf is never executed. My original attempt was to fill each slot of the array with a double, but since that didn't work I simplified the program to this, but this doesn't work either.

I'm a beginner learning C, so I probably made a stupid mistake I just can't see. Any help would be appreciated, thanks!

Edit:

Okay, so apparently I need to add an ampersand to the scanf statement. But I thought an array was just a pointer to the first element of the array? Why do I have to use the ampersand?

解决方案

scanf("%f", values[0]); - Here address of first element should be passed to scanf. You are passing value of first element which is a garbage value so that it crashed.

values[0] is *(values + 0), so this will give value of the first element not the address of the first element.

Do scanf("%lf", &values[0]); or scanf("%lf", (values + 0)); or scanf("%lf", values);

As it is double use %lf instead of %f.

One more problem in your program is uninitlized variables. Try to initialize the variable to zero while declaring.

double values[8] = {0};
double cumulative[8] = {0};

Acessing some wrong pointer in some place of your code will leads to 100% crash if its initiliazed to zero. Otherwise it will try to access some garbage value pointer which will leads to memory corruption, this sometimes will not crash instead will give unexpected output. But this also has a 50% chance of getting crash, which you are getting now.

这篇关于尝试将浮点数读入数组时,scanf崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆