简体   繁体   中英

C - Sorting in dynamic array doesn't work for specific number of values

My task is to create a sorting algorithm for integer values read from a file. The values have to be sorted in an array, as the amount of values is variable, I've used a dynamic array of integers (actually my first time).

Now, the algorithm seems to work fine as it prints all values in the correct order, but only until there are 6 values to sort. In that case, there's no output whatsoever, it seems like even the sorting process isn't successful anymore.

Here's my code:

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

void swap(int *a, int *b){
..
}

int main(){
    int i,anzahl,sorted=0,bla;
    FILE *fp;
    int* feld;

    fp=fopen("file","r");
    if (fp==NULL) return 0;
    else {
        fscanf(fp,"%i",&anzahl);
        feld=(int*)calloc(anzahl,sizeof(int));
        for (i = 0; i <= anzahl; ++i) {
            fscanf(fp,"%i",&bla);
            *(feld+i)=bla;
        }
        fclose(fp);
        while (sorted==0){
            for (i = 0; i < anzahl-1; ++i) {
                if (feld[i]>feld[i+1]) swap(&feld[i],&feld[i+1]);
            }
            for (i = 0; i < anzahl-1; ++i) {
                if (feld[i]<=feld[i+1]) sorted=1;
                else {sorted=0; break;}
            }
        }
        for (i = 0; i <anzahl; ++i) {
            printf("%i ",feld[i]);
        }
    }
    return 0;
}

Please excuse the German variable names and the newbie-style code.

If now the content of my "file" is as follows:

6
1
5
1
99
7
8

the program won't work. If I change the number of values, everything is fine, but as long as the number of values is 6, the program won't work, no matter what values there are.

You are going out of bounds causing undefined behavior here:

for (i = 0; i <= anzahl; ++i)
               ^

This line should be comparing less than not equal or less than .

Also checking calloc() return value is always a good idea.

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