Well, as part of learning C++, my project has a restriction on it. I'm not allowed to use any libraries except the basic ones such as <cstring>
and a few other necessities.
The project should take in input from a file that is an "n" number of columns of strings and be able to sort the output according to lexicographical ordering of any selected column. So for example, given the input
Cartwright Wendy 93
Williamson Mark 81
Thompson Mark 100
Anderson John 76
Turner Dennis 56
It should sort them by column. And my search around StackOverflow returned a result from someone else who had to do the exact same project a few years ago too Hahaha Qsort based on a column in a c-string?
But in my case I just use a global variable for the column and get on with life. My problem came in when I am implementing the compare function for qsort
In my main method I call
qsort (data, i, sizeof(char*), compare);
where data is a char * data[]
and i
is the number of lines to compare. (5 in this case)
Below is my code for the compare method
int compare (const void * a, const void * b){
char* line1 = new char[1000]; char* line2 = new char[1000];
strcpy(line1, *((const char**) a));
strcpy(line2, *((const char**) b));
char* left = &(strtok(line1, " \t"))[column-1];
char* right = &(strtok(line2, " \t"))[column-1];
return strcmp(left, right);
}
the 1000s are because I just generalized (and did bad coding on purpose) to overgeneralize that no lines will be longer than 1000 characters.
What confuses me is that when I use the debugger in Eclipse, I can see that it it compares it successfully the first time, then on the second round, it has a segmentation fault when it tries to compare them.
I also tried to change the code for assigning left and right to what is below but that didn't help either
char* left = new char[100];
strcpy(left, &(strtok(line1, " \t"))[column-1]);
char* right = new char[100];
strcpy(right, &(strtok(line2, " \t"))[column-1]);
Please help me understand what is causing this segmentation fault. The first time it compares the two, left = "Williamson" and right = "Thompson". The second time it compares (and crashes trying) left = "Cartwright" and right = "Thompson"