I am writing code to sort a txt file of int's and then display them when the user asks for a number at a certain index but every time I run my code I get a segmentation fault. What can I do to fix this?
void insert_sorted(long *sorted, int count, long value)
{
int i = 0;
sorted[1024] = value;
if (count == 0) return;
for (i = count; i >= 0; i--) {
if (value < sorted[i - 1])
sorted[i] = sorted[i - 1];
else break;
}
sorted[i] = value;
}
int main(int argc, char *argv[])
{
FILE *infile = NULL;
int count = 0;
long sorted[1024];
long value;
int i = 0;
if (argc < 2) {
fprintf(stderr, "Usage : %s <file_name>/n", argv[0]);
return 1;
}
infile = fopen(argv[1], "r");
if (NULL == infile) {
perror("fopen");
return -1;
}
/* while file not ends */
while (!feof(infile)) {
fscanf(infile, "%ld\n", &value); /* fetch value */
insert_sorted(sorted, count, value); /* sort */
++count; /* increase number of sorted values */
}
/* display values */
printf("Enter Index : ");
int index;
scanf("%d", &index);
if (index == -1)
fclose(infile);
printf("%d ", sorted[index]);
/* cleanup */
if (infile) {
fclose(infile);
infile = NULL;
}
return 0;
}