C++ What does size parameter in qsort do -


in qsort:

void qsort (void* base, size_t num, size_t size, int (*compar)(const void*,const void*)); 

documentation explains:

size size in bytes of each element in array. size_t unsigned integral type. 

but qsort invoked qsort(...,...,sizeof(int),...), or qsort(...,...,sizeof(char *),...)

if understanding correctly, since size of string can not determined, not matter anymore, instead use sizeof(char*) type declaration.

any explanations?

qsort requires contiguous block of memory can treated array. becaue of that, each item in array must same size, , provide size qsort when call it.

if want store actual strings in array, they'll need same size, size of largest one.

and, when comparison function compares them, qsort move around massive amounts of memory complete sort, since swap strings themselves.

far more usual have strings stored outside of array area , use array store pointers strings. pointers swapped they're going smaller on average strings point at.

for example, with:

char *strings[] = {"xyzzy", "zorkmid", "twisty little passages", "plugh"}; 

the strings array consists of 4 pointers strings, each pointer taking 4 bytes (on system, yours may different). when qsort sorts array, things moved around within array pointers.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -