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]);orscanf("%lf", (values + 0));orscanf("%lf", values);As it is
doubleuse%lfinstead of%f.One more problem in your program is uninitlized variables. Try to initialize the variable to zero while declaring.
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.