I am working on a program that takes an arbitrary number of arguments from the command line, cuts them in half, puts them in an array, sorts them alphabetically, then prints them in order. It works fine up to three arguments, but is giving some strange output after that. Output Here is what I have so far:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct string {
char *first_half;
char *second_half;
};
int cstring_cmp(const void *a, const void *b);
int arrayIndex = 0;
int main(int argc, char *argv[])
{
int numArguments = argc;
char **new_array = malloc(argc * sizeof(char*));
struct string word;
for (int i = 1; i < argc; i++)
{
int len = strlen(argv[i]);
int len_first = len/2;
int len_second = len - len_first;
word.first_half = malloc( (len_first + 1) * sizeof(char) );
word.second_half = malloc( (len_second + 1) * sizeof(char) );
memcpy(word.first_half, argv[i], len_first);
memcpy(word.second_half, argv[i]+len_first, len_second);
new_array[arrayIndex] = word.first_half;
if(word.second_half != " ")
new_array[arrayIndex+1] = word.second_half;
arrayIndex += 2;
//free(word.first_half);
//free(word.second_half);
}
qsort(new_array, ((argc - 1)*2), sizeof(char *), cstring_cmp);
for (int i = 0; i < ((argc - 1)*2); ++i)
{
printf("%s\n", new_array[i]);
}
return 0;
}
int cstring_cmp(const void *a, const void *b)
{
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return strcmp(*ia, *ib);
}