helsereet
helsereet

Reputation: 111

Program stops after loop in function

My prog doesn't reach outArray function. it stops after loop of fillArray function. Why this happens. It looks strangely, cause it's simple void function and shouldn't return anything. This should continue run commands in main. And that stops as usual program without any problems and bugs

#include <stdio.h>
#define N 100

int enterNofArray();
void fillArray(int n, float arr[N]);
void outArray(int n, float arr[N]);

int main()
{
    float arr[N], sum = 0.0, average;
    int n;

    //input
    n = enterNofArray();

    //compute
    fillArray(n, &arr[N]);

    //output
    outArray(n, &arr[N]);

    return 0;
}


int enterNofArray()
{
    int n;
    printf("Enter amount of array...\n");
    scanf("%d", &n);

    while (n < 1 || n > N)
    {
        printf("Incorrect!!\n");
        printf("Enter in range 1 - 100...\n");
        scanf("%d", &n);
    }

    return n;
}

void fillArray(int n, float arr[N])
{
    int num;
    for(int i = 0; i < n; i++)
    {
        printf("Enter number for array[%d times left]...\n", n - i);
        scanf("%d", &num);
        arr[i] = num;
    }
}

void outArray(int n, float arr[N])
{
    for(int i = 0; i < n; i++)
    {
        printf("%f ", arr[i]);
    }
}

Upvotes: 1

Views: 990

Answers (2)

Leonardo
Leonardo

Reputation: 1

Because you're send double pointer when you do this:

fillArray(n, &arr[N]); outArray(n, &arr[N]);

Looks like:

fillArray(n, **arr); outArray(n, **arr);

This happends so much when you work with Structures.

Upvotes: 0

gsamaras
gsamaras

Reputation: 73384

&arr[N] refers to the memory location (or lvalue) that contains the N-th (out of index!!!) element in the array.

That code invokes Undefined Behavior (UB).

So, you weren't actually passing the whole array to your functions, you were just attempting to pass the N-th element of that array... Read more about that expression here.

Change this:

fillArray(n, &arr[N]);
outArray(n, &arr[N]);

to this:

fillArray(n, arr);
outArray(n, arr);

Live Demo

The problem was that with your code n was corrupted, containing garbage value after the call to fillArray function. As a result, when outArray function was called, n had a garbage value, which resulted in an uncontrolled for-loop that ended in looping far further than the limits of your array, eventually accessing memory that you didn't own, thus causing a Segmentation Fault.


Not the cause of your problem, but I suggest you do scanf("%f", &num); in your fillArray function (after declaring num as a float of course), since you want to populate an array of floats.

Upvotes: 3

Related Questions