valaris : thanks, but your suggestions didn't work for me.
i don't know how to make this damn thing run using a pointer to a pointer, so i'm just gonna stick with returning the pointer at the end of the function (this now makes alot of sense to me).
I've also updated a few coding faux pas (except 2):
some serious
Code:
integers = malloc(*num1 * sizeof(int)); to integers = malloc((*num1 + 1) * sizeof(int));
Code:
int *integers = 0; // undefined behavior bad
int num1 = 0;
some not so serious
Code:
main() to int main(void)
Code:
int *allocate_memory(int *integers, int *num1); // not just the prototypes
int average_of(int *integers, int *num1);
int print_average(int *integers, int *num1);
some just plain stupid (in an attempt to understand)
But.....
1)fflush(stdin) must stay, because the getchar() doesn't work if its not there...see for yourself, it doesn't wait for a character return.
matsp: fflush(stdout) does not make sense to me. It flushes the standard output, after those scanfs i have to flush the standard input to do a getchar().
2)Between copying a value in to a function (int num1) vs copying a pointer to a value in to a function (int *num1). I don't know whether one or the other is more efficient, or if they are equal. I know i'm not changing the value of num1 (except in the allocate_memory function), but do i really need to change all of the other int *num1's to int num1's... ?
heres my code:
Code:
#include <stdio.h>
#include <stdlib.h>
int *allocate_memory(int *integers, int *num1);
int average_of(int *integers, int *num1);
int print_average(int *integers, int *num1);
int *allocate_memory(int *integers, int *num1)
{
printf("How many numbers do you want to average: ");
scanf("%d", num1);
integers = malloc((*num1 + 1) * sizeof(int));
if(integers == NULL)
{
printf("malloc has failed\n");
exit(1);
}
return integers;
}
int average_of(int *integers, int *num1)
{
int i;
integers[*num1] = 0;
for(i = 0; i < *num1; i++)
{
printf("#%d Please enter a number: ", i + 1);
scanf("%d", &integers[i]);
integers[*num1] += integers[i];
}
integers[*num1] /= *num1;
}
int print_average(int *integers, int *num1)
{
int i;
printf("The average of ");
for(i = 0; i < *num1; i++)
printf("%d ", integers[i]);
printf("is : %d\n", integers[*num1]);
}
int main(void)
{
int *integers = 0;
int num1 = 0;
integers = allocate_memory(integers, &num1);
average_of(integers, &num1);
print_average(integers, &num1);
free(integers);
fflush(stdin);
getchar();
return 0;
}
Thanks again, to everyone who has posted so far.