by pistoleer · 2y ago · 0 comments
void (*name)(char *ptr);
typedef void (*name_func)(char *ptr);
void target(void *ptr)
{
printf("Input %p\n", ptr);
}
char *data = "string";
name = (name_func)target; // Illegal: casting fn that takes void* to a fn that takes char*
name(&data); // Illegal: passing a char** into a function that takes char*
Before someone mentions qsort(): the comparator function really is supposed to take a void*, and inside the function, you re-cast the void* argument to a pointer type of your desire. If you don't do it in that order, you're using it wrong. /* declarations */
void qsort(void *lineptr[], int left, int right,
int (*comp)(void *, void *));
int numcmp(char *, char *);
/* the offending line */
qsort((void **) lineptr, 0, nlines-1,
(int (*)(void*,void*)(numeric ? numcmp : strcmp));In the GP example, a char** is passed where a char* is expected. That is clearly invalid.
> Before someone mentions qsort(): the comparator function really is supposed to take a void*, and inside the function, you re-cast the void* argument to a pointer type of your desire. If you don't do it in that order, you're using it wrong.
In contrast, the K&R example is an example of explicitly undefined behavior in the C standard:
The behavior is undefined in the following circumstances:
- A pointer is used to call a function whose type is not compatible with the pointed-to type (6.3.2.3).
You can’t blame K&R C for that. It predates “the C standard” by over a decade (1978 vs 1989)
When it was written, what K&R said was C.
I assume this is just a typo in the article. He probably meant `name(data)`.