简体   繁体   中英

Sum and average of numbers within an array C

I'm confused on how to calculate the mean and the sum of the numbers within an array, I can generate the numbers but the program keeps crashing. I'm very new to arrays and pointers any help/information helps. thanks!

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int sum(int *myInts)
{
    int sum=0,i;

    for(i=0; i < 20; i++){
        sum += myInts[i];
    }
    return sum;
}

int mean(int *myInts)
{
    int mean=0,i;

    for(i=20; i < 20; i++){
        mean += myInts[i] / 20;
    }
    return mean;
}

int main(int i)
{
    srand(time(NULL));
    int *myInts[20];

    for(i=0; i < 20 ; i++){
        myInts[i] = rand() % 15;
    }
    printf("The array is: ");
    for(i=0; i < 20; i++){
        printf(" %d", myInts[i]);
    }
    printf("\nThe sum of the array is: %d", sum(myInts[20]));
    printf("\nThe mean of the array is: %d", myInts[20],mean(myInts[20]));

    getchar();
    return 0;
}
int *myInts[20];

Here, you've declared an array of pointers to int , not an array of int. Within the main function you get away with it because integers can be converted to pointers and back, but it becomes an issue when you call the function:

sum(myInts[20])

This passes the array element with offset 20 to the function. Because array indexes start with 0, an array of size 20 has indexes from 0 to 19. So you read past the end of the array, then in the function this value it treated as a pointer and dereferenced. This invokes undefined behavior which is what causes the crash.

You instead want to declare an array of int :

int myInts[20];

And pass the array to the function:

sum(myInts);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM