我正在为一个项目上课,我去测试我已经完成的部分并且出现了堆损坏错误
#include <stdio.h>
#include <stdlib.h>
double findMean(double a[], unsigned int size)
{
double total = 0;
double mean;
for (unsigned i = 0; i < size; ++i)
{
total = total + a[i];
}
mean = total / (double)size;
return mean;
}
int main(int argc, char *argv[])
{
int size; // the number of elements
double *array; // pointer to the array, will be allocated by malloc
if (argc < 2)
{
// if argc is 1, there are no command line arguments
printf("no arguments\n");
return 1;
}
size = atoi(argv[1]); // convert the string argument to a number
if (size > argc - 2)
{
// there should be exactly size+2 strings on the command line including the program name argv[0] and the number of elements argv[1].
printf("%d missing arguments\n", size - (argc - 2));
return 2;
}
if (size < argc - 2)
{
// here there are too many command line arguments
printf("%d extra arguments\n", (argc - 2) - size);
return 3;
}
// allocate memory for the array: size elements, each having the size of an int */
array = malloc(sizeof(int) * size);
if (array == NULL)
{
// if memory cannot be allocated, malloc() returns a NULL pointer
printf("cannot allocate array\n");
return 4;
}
//convert the command line arguments from 2 to size+1 to doubles and store them into the array
for (int i = 0; i < size; i++)
{
array[i] = strtod(argv[2 + i], NULL);
}
printf("Results:");
double min = array[0]; //Element zero of sorted array will be minimum
printf("\nmin = %.3lf ", min);
double max = array[size - 1];
printf("\nmax = %.3lf", max);
double mean = findMean(array, size);
printf("\nmean = %.3lf", mean);
free(array);
}
真正奇怪的是,即使程序由于错误而崩溃,它仍然会执行它应该做的所有事情,所以我不知道出了什么问题。
答案 0 :(得分:2)
double *array; // pointer to the array, will be allocated by malloc
/* ... */
// allocate memory for the array: size elements, each having the size of an int
array = malloc(sizeof(int) * size);
当然应该是sizeof(double)
。