Я работаю далеко над проектом для класса, и я пошел, чтобы проверить часть я закончил и получил ошибку кучи коррупцииHeap ошибка коррупции
#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);
}
Действительно странно, даже несмотря на сбои программ из-за ошибки, он все еще делает все, что он должен делать, поэтому я не знаю, что происходит.
Пожалуйста, укажите полное сообщение об ошибке, которое вы видите в вопросе. –
Используйте отладчик или операторы печати, чтобы выяснить, какая строка сбой. – John3136