void pointer arithmetic

H

Hallvard B Furuseth

Jeremy said:
I think this needs to be something like:

int compare(const void *s1, const void *s2)
{
return strcmp(*(char **)s1 + OFFSET, *(char **)s2 + OFFSET);
}

Or

int compare(const void *s1, const void *s2)
{
return strcmp(*(char *const *)s1 + OFFSET,
*(char *const *)s2 + OFFSET);
}

If you want to avoid some compilers' warnings about casting
away 'const'.
 
J

Jeremy Yallop

Hallvard said:
Or

int compare(const void *s1, const void *s2)
{
return strcmp(*(char *const *)s1 + OFFSET,
*(char *const *)s2 + OFFSET);
}

Sure. I think that counts as "something like". In this case I find
that the extra "const" makes the code more difficult to read. I might
add it if using extra local variables instead of casting.
If you want to avoid some compilers' warnings about casting
away 'const'.

There should be a way to turn that warning off without changing the
code. Casting away const is sometimes necessary (e.g. to implement a
function with an interface like strstr()). (Okay, not strictly
/necessary/ - you can use memcpy() instead, for example - but
"necessary in sane code").

Jeremy.
 
C

CBFalconer

Jeremy said:
Sure. I think that counts as "something like". In this case I
find that the extra "const" makes the code more difficult to read.
I might add it if using extra local variables instead of casting.


There should be a way to turn that warning off without changing
the code. Casting away const is sometimes necessary (e.g. to
implement a function with an interface like strstr()). (Okay,
not strictly /necessary/ - you can use memcpy() instead, for
example - but "necessary in sane code").

/* invalid for strlen(s) < OFFSET */
int compare(const void *s1, const void *s2)
{
const char *p1 = s1;
const char *p2 = s2;

return strcmp(p1 + OFFSET, p2 + OFFSET);
}
 
J

Jeremy Yallop

CBFalconer said:
/* invalid for strlen(s) < OFFSET */
int compare(const void *s1, const void *s2)
{
const char *p1 = s1;
const char *p2 = s2;

return strcmp(p1 + OFFSET, p2 + OFFSET);
}

No, this is wrong. You need an extra level of indirection. The
pointers passed to the comparison function are pointers to the objects
in the array. That is, they're pointers to pointers to char disguised
as pointers to (const) void. If you want to write the comparison
function in this way you can write:

int compare(const void *s1, const void *s2)
{
const char *const *p1 = s1;
const char *const *p2 = s2;

return strcmp(*p1 + OFFSET, *p2 + OFFSET);
}

(with more or fewer "const"s according to taste).

Jeremy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,104
Messages
2,570,643
Members
47,247
Latest member
youngcoin

Latest Threads

Top