Program crashes I suspect variable n but I'm not a 100% sure. I showed this code to my teacher and we tried different things to solve the crash. But without a single warning and error from Bloodshed's C++ it's hard to pin point the cause of the problem.
Still I'm pretty certain it has something to do with variable n. Since the array variable code worked in previous testings.
My teacher says that I have overcomplicated the assignment and don't need to make the code so functional and pretty. So I could theoretically speaking solve this assignment in a really ugly way.
But I've already spent over 2 weeks over-complicating things and like to know what horrible mistakes I've done. Before I ditch the code and do things the quick and ugly way.
Why does this program crash?
Have I forgotten to initialize variable n in main(void)?
Code:
/* Sum numbers 0 ... 9 two at a time */
/* index increments */
/* sum() function uses "pass by reference" */
/* even if it's only about one "return value" */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void sum(double a, double b, double* summa);
void input(double* array, int* n);
int main(void)
{
double* array;
int n;
int i;
/*
Teacher says that pointers are only necessary when you have to pass several values.
Variable n only contains one value so it doesn't need a pointer!
*/
//______________________________________________________________________________
/* Input */
input(array, &n);
printf("%d", n);
//______________________________________________________________________________
/* Sum */
for( i=0; i<n-1; i++)
{
sum(array[i], array[i+1], &array[i+1]);
printf("Partial sum %d equals: %.2lf\n", i+1, array[i+1]);
}
printf("\nGrandtotal equals: %.2lf\n", array[n-1]);
printf("\n");
printf("__________________________________________");
printf("\n\n");
free(array);
system("PAUSE");
return 0;
}
/*************
* Functions
*************/
//______________________________________________________________________________
/* Sum */
void sum(double a, double b, double* summa)
{
*summa = a + b; /* return with "pass by reference" */
}
//______________________________________________________________________________
/* Input */
void input(double* array, int* n)
{
int i;
printf("How many numbers do you want to input? --> "); scanf("%d", &n);
// calloc = Memory allocation for array.
array = calloc(*n, sizeof *array);
for(i=0 ; i<*n ; i++)
{
printf("\n\nInput a number, for element number <%d>. --> ", i);
scanf("%lf", array+i);
}
// Confirm input values.
for(i=0 ; i<*n ; i++)
printf("\n< Element number %d > , = %.2lf", i, array[i]);
printf("\n\n");
printf("______________________________________________________________");
printf("\n\n");
}
//______________________________________________________________________________