c - Is casting to pointers to pointers to void always safe? -


#include <stdio.h>  void swap(void *v[], int i, int j) {     void *tmp;      tmp = v[i];     v[i] = v[j];     v[j] = tmp; }  int main(void) {     char *s[] = {"one", "two"};     printf("%s, %s\n", s[0], s[1]);     swap(s, 0, 1);     printf("%s, %s\n", s[0], s[1]);     return 0; } 

output:

one, 2  two, 1 

warning: no compatible pointer casting, need void**, char

i used program simulate swap function in k&r, demonstrate use of function pointer, , question whether cast of void pointer safe, or if there way replace it.

no, not safe pass char** void** (which void*[] function parameter is) expected. fact compiler makes perform explicit cast hint that.

in practice, fine. strictly speaking, however, have no guarantee sizeof (t*) == sizeof (u*) distinct types t , u. (for example, imagine hypothetical system sizeof (int*) < sizeof (char*) because pointers-to-int aligned , therefore don't need store least significant bits.) consequently, swap function might index v array using wrong offsets.

also see q4.9 comp.lang.c faq: can give formal parameter type void **, , this?

to call swap safely, should like:

void* temp[] = { &s[0], &s[1] }; swap(temp, 0, 1); 

although swap elements of temp, not of s.

if you're authoring swap, in general should make such function take void* argument (instead of void** one) , size_t argument specifies size of each element. function cast void* char* safely , swap individual bytes:

void swap(void* p, size_t elementsize, size_t i, size_t j) {     char* item1 = p;     char* item2 = p;      item1 += * elementsize;     item2 += j * elementsize;      while (elementsize-- > 0) {         char temp = *item1;         *item1 = *item2;         *item2 = temp;         item1++;         item2++;     } } 

edit: see this stackoverflow answer similar question.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -