Note that there are some explanatory texts on larger screens.

plurals
  1. POSorting a 2 dimensional array of strings by a specific field
    text
    copied!<p>Given a two dimensional array decalred below:</p> <pre><code>char * Arr[4] = { {"124 -346 DATA...."}, {"39479 -32 MOREDATA...."}, {"12 -1 DATA2...."}, {"100 -45 DATA4...."} }; </code></pre> <p>i'm trying to use <a href="http://www.cplusplus.com/reference/cstdlib/qsort/" rel="nofollow">qsort()</a> to sort this function according to the <strong>SECOND</strong> field, meaning the strings would be ordered according to the lowest second value(-1,-32,-45,-346). I know how to make this function if each value were only one digit, but the digits in the program could be arbitrarily long. here is what i have but the program crashes, if there is a more efficient way to sort this data i would love to here it(i know my method can't be very efficient).</p> <p>Sort function(which qsort() calls):</p> <pre><code>inline void GetStr(char *ix, char* Result) //call to get second number in function { char *spacing; //iterator to traverse spacing = ix; //iterator = pos of ix int LEN = 0; //length and offset int Offset = 0; while(*spacing != ' ') //while not at end of first num { Offset++; //offset is more spacing++; } spacing++; //go one ahead of the space Offset++; while(*spacing != ' ') //while not end of second number { spacing++; Offset++; LEN++; //length of number } strncpy(Result, ix + (Offset - LEN),LEN); } int sort(const void* a, const void* b) { char *ia = *(char**)a; char *ib = *(char**)b; char * Str; char * Str2; GetStr(ia, Str); //getting some strange errors....... program just crashes GetStr(ib, Str2); printf("Str: %s Str2: %s", Str, Str2); int n1 = atoi(Str); int n2 = atoi(Str2); return (n1 &gt; n2); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload