Can anyone tell why this C function isn't working?

Viewed 70

So, I'm doing an exercise, and I want to sort a list of float numbers. When I used for loop, it worked perfectly. When I changed to while loop, it shows nothing. I already tried to declare a different variable for each while loop, but remains the same. I'm getting this warning for the file ex005.c:

Please, input one non-integer values: 45.3
Please, input one non-integer values: 32.2
Please, input one non-integer values: 34.5
zsh: segmentation fault  ./"ex005"

Here is my code:

#include <stdio.h>

int main(void)
{
    float   three_numbers[3];
    char    support_var;
    int     size_array;
    int     i;
    int     z;

        size_array = 3;
        z = size_array - 1;
        i = 0;
    while (i < size_array)
    {
        printf("Please, input one non-integer values: ");
        scanf("%f", &three_numbers[i]);
        i++;
    }
    i = 0;
    while (i < size_array)
    {
        while (z != i)
        {
            if (three_numbers[i] < three_numbers[z])
            {
                support_var = three_numbers[i];
                three_numbers[i] = three_numbers[z];
                three_numbers[z] = support_var;
            }
            z--;
        }
        i++;
    }
    i = 0;
    while (i < size_array)
    {
        printf("The %dth place is %.1f. \n", i + 1, three_numbers[i]);
        i++;
    }
    return (0);
}
1 Answers

You probably want to set z in the inner loop otherwise it causes out of bound access of three_numbers[z]. Also, your support_var should be a float. Use the typeof operator if available (with gcc 10.2.1-6 it's still an extension so -std=gnu18):

#include <stdio.h>

#define ARRAY_SIZE 3

int main(void) {
    float three_numbers[ARRAY_SIZE];
    for(int i = 0; i < ARRAY_SIZE; i++) {
        printf("Please, input one non-integer values: ");
        scanf("%f", three_numbers + i);
    }
    for(int i = 0; i < ARRAY_SIZE; i++) {
        for(int z = ARRAY_SIZE - 1; z != i; z--) {
            if(three_numbers[i] < three_numbers[z]) {
                // typeof (*three_numbers) support_var = three_numbers[i];
                float support_var = three_numbers[i];
                three_numbers[i] = three_numbers[z];
                three_numbers[z] = support_var;
            }
        }
    }
    for(int i = 0; i < ARRAY_SIZE; i++) {
        printf("The %dth place is %.1f. \n", i + 1, three_numbers[i]);
    }
}

Not sure why you don't like for-loops but it makes your code easier to read. Also replaced int array_size with a constant ARRAY_SIZE. Minimizing scope of variables makes is usually a good idea.

Related