Using and dereferencing (void**)

做~自己de王妃 提交于 2019-12-05 05:15:01
Grijesh Chauhan

Note: void* is generic. but void** is not. You can assign address of any type to void* variable but void** can be assigned address of void* variable only.

void* generic;
int i;
int *ptri = &i;

generic = ptri;

or

char c;
int *ptrc = &c;

generic = ptrc;

valid but following is an error:

void**  not_generic;
int i;
int *ptri = &i;
int **ptr_to_ptr1 = &ptri;
void**  not_generic = ptr_to_ptr1;

Error: assigning int** to void**.

Yes you can do like:

void**  not_generic;
not_generic = &generic;

For generic array function simply use void* a as follows:

enum {INT, CHAR, FLOAT};
void print_array(void* a, int length, int type){
   int i = 0;
   for(i = 0; i < length; i++){
      switch(type){
         case INT: 
              printf("%d", *((int*)a + i));
              break;
         case CHAR: 
              printf("%c", *((char*)a + i));
              break;
         case FLOAT: 
              printf("%f", *((float*)a + i));
              break;
      }
   }
}

You better write this function using macros.

Call this function as:

Suppose int:

 int a[] = {1, 2, 3, 4}; 
 print_array(a, sizeof(a)/sizeof(a[0]), INT);

Suppose char:

 char a[] = {'1', '2', '3', '4'}; 
 print_array(a, sizeof(a)/sizeof(a[0]), CHAR);

Because there is no generic pointer-to-pointer type in C.

Reference: C FAQ Question 4.9

The short answer is: anything that resembles

<datatype>* <variable_name>

can be passed in where the parameter declaration is of type void* because void* is generic. However, void** is not. So automatic casting fails.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!