I am having trouble sorting out a list of names in c. I have code for sorting the names, but when I go to print them out they still are in the same order as they were at the beginning so something isnt right. So the function that I need help with is the sort_data function. I will post all of my code so it can help you guys out with helping me! Thanks a lot in advance, this function has been killing me all morning.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LEN 25
void insert_data(char **strings, const char* filename, int size);
void allocate(char ***strings, int size);
void sort_data(char **strings, int size);
int main(int argc, char* argv[]){
if(argc != 4){
printf("Wrong number of args");
}
char **pointer;
int size = atoi(argv[1]);
allocate(&pointer, size);
insert_data(pointer, argv[2], size);
sort_data(pointer,size);
}
void sort_data(char **strings, int size){
int i, j;
char temp[MAX_STRING_LEN];
for( i = 1; i < size; i++){
strcpy(temp, strings[i]);
j = i - 1;
while( j >= 0 && strcmp(strings[i], temp) > 0)
{
strcpy(strings[j+1], strings[j]);
j = j - 1;
}
strcpy(strings[j+1], temp);
}
int z;
for(z = 0; z < size; z++){
printf("\n%s", strings[z]);
}
}
void allocate(char ***strings, int size){
int i;
*strings = malloc(sizeof(**strings) * size);
for( i = 0; i < size; i++)
{
(*strings)[i] = malloc(sizeof(char) * MAX_STRING_LEN);
}
}
void insert_data(char **strings, const char* filename, int size){
FILE *input;
input = fopen(filename, "r");
int i;
for (i = 0; i < size; i++){
fscanf(input,"%24s", strings[i]);
}
fclose(input);
}
The list that I am reading in is as follows:
- matt
- susan
- mark
- david
- aden
- phil
- erik
- john
- caden
- mycah
So I need to get this list in alphabetical order, but when I run my code and print out this list after I run the sort function, they are still in this order. Thanks alot once again for the help.