If I paste this program in a compiler(I use Notepad ++ ) and then i try to run i
ID: 3622380 • Letter: I
Question
If I paste this program in a compiler(I use Notepad ++ ) and then i try to run it, it gives me an error: Error 2140 line 40:// Max, Min, Average
// Created By Nic Raboy
// November 23rd 2010
#include <stdio.h>
#include <stdlib.h>
// Loop through all the inputed values summing them up. After all values
// have been summed then divide by the total number of values
float calcAverage(int *s, int l) {
int avg = 0, x = 0;
for(x = 0; x < l; x++) {
avg += s[x];
}
return (float)avg / l;
}
// Loop through all the inputed values and replace the current minimum
// with the new minimum from the array
int calcMin(int *s, int l) {
int min = 999999, x = 0;
for(x = 0; x < l; x++) {
if(min > s[x])
min = s[x];
}
return min;
}
// Loop through all the inputed values and replace the current maximum
// with the new maximum from the array
int calcMax(int *s, int l) {
int max = 0, x = 0;
for(x = 0; x < l; x++) {
if(max < s[x])
max = s[x];
}
return max;
}
int main() {
int total = 0, x = 0;
printf("How many stocks will you enter? ");
scanf("%d", &total);
int *stocks = (int*)malloc(total); // Allocate an integer array based on the number entered
for(x = 0; x < total; x++) {
printf("Stock #%d> ", x+1);
scanf("%d", &stocks[x]);
}
// Use the functions we just made
printf("Average: %.2f ", calcAverage(stocks, total));
printf("Minimum: %d ", calcMin(stocks, total));
printf("Maximum: %d ", calcMax(stocks, total));
free(stocks); // Free the array
return 0;
}
// Max, Min, Average
// Created By Nic Raboy
// November 23rd 2010
Explanation / Answer
This error seems to occur only on MS Windows compilers. The error occurs because the function 'free()' is expecting an array that has already become NULL. By doing the following it seems to fix the issue on Windows. -------------- // Use the functions we just made printf("Average: %.2f ", calcAverage(stocks, total)); printf("Minimum: %d ", calcMin(stocks, total)); printf("Maximum: %d ", calcMax(stocks, total)); stocks = NULL; free(stocks); // Free the array return 0; -------------- Notice how I made 'stocks = NULL;' before calling the free function. I tested this with the Visual C++ 2010 compiler and GCC on my Macintosh and both seem to work. I hope this solves your problem as well. If it does not, let me know.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.