in c, if i have char *const* pointer, how do i access each and every element? -
this qsort comparison function,
int cmp(const void *p, const void *q) {     char *const* pp = p;     char *const* qq = q;     ... } i want compare elements of 2 strings. tried (*pp)[i] since *pp p, doesnt seem work. also, advantage of catching p , q way instead of creating 2 const char *?
last no least, have comparison function supposed skip leading white spaces
int wcmp(const void *p, const void *q) {      const char *pp = p;     const char *qq = q;     size_t = 0;     size_t j = 0;      while(isspace(*(pp+i))) {         i++;     }      while(isspace(*(qq)+j)) {         j++;     }      return strcmp(pp+i, qq+j); } but when test
    d afdsa    hello   heal the output is
  heal     d afdsa    hello what going on "d afdsa" in middle?
qsort works elements of any size. way can work passing pointers first bytes of elements, , these of type const void *.
so if have array of ints, comparison function gets 2 pointers void, points 2 ints in array, , compare pointed-to objects:
int cmp(const void *p, const void *q) {     int *pp = p;     int *qq = q;     return *pp - *qq; // example, ignoring possible ub , such. } likewise, if have array of pointers char, i.e. char *array[], each element pointer char, , comparison function gets passed in 2 arguments: pointers const void point these elements. when cast them get: 
char *const *pp = p; i.e. pointer constant pointer char. actual objects must compare pointed-to these pointers.
and why wcmp doesn't work:
int wcmp(const void *p, const void *q) {     const char *pp = p;     const char *qq = q;     ... } this appropriate if each element in array sorted char. elements pointers char, means arguments wcmp (each of points element in array) must converted pointers pointers char:
int wcmp(const void *p, const void *q) {     char *const *ptmp = p;     char *const *qtmp = q; then must dereference them actual pointer char
    char *pp = *ptmp; // dereference them     char *qq = *qtmp;  or, can shorten 2 to:
    char *pp = *(char *const *)p;     char *qq = *(char *const *)q; as rest of wcmp, that's not c - true c programmer loves changing pointers:
    while(isspace(*pp)) {         pp ++;     }      while(isspace(*qq)) {         qq ++;     }      return strcmp(pp, qq); } that is, long pp points space character, increment pp points next character; , same qq too, , compare strings first characters pointed pp , qq.
Comments
Post a Comment