Joe Pfeiffer
6/4/2011 11:00:00 PM
"Bill Cunningham" <nospam@nspam.invalid> writes:
> I get a segmentation fault with this code. I'm not quite sure what's
> wrong with it I've looked and looked. It might help if I knew what the
> nature of a seg fault was.
>
> #include <stdio.h>
>
> double mean(double *avg, int num)
> {
> double sum, average;
> int i;
> sum = average = 0;
> for (i = 0; i < num; ++num) {
> sum = sum + avg[num];
> average = sum / num;
> }
> return average;
> }
>
> int main()
> {
> double a[] = { 2.5, 3, 4.6 };
> printf("%.2f\n", mean(a, 3));
> return 0;
> }
A segmentation fault is an attempt to access memory you don't have
access rights to. When a program segfaults, there is a near certainty
that there is either a bad pointer, or an array access out of range.
Your for-loop sets i to 0, and then checks to make sure it's less than
num before continuing. It then uses num to index the array, and
increments num. This is probably not what you want to be doing.
--
"Erwin, do you know what happened to the cat?" -- Mrs. Shroedinger