How to make generic function using void * in c?

后端 未结 7 2289
广开言路
广开言路 2020-12-13 07:48

I have an incr function to increment the value by 1 I want to make it generic,because I don\'t want to make different functions for the same functi

7条回答
  •  独厮守ぢ
    2020-12-13 08:27

    Example for using "Generic" swap.

    This code swaps two blocks of memory.

    void memswap_arr(void* p1, void* p2, size_t size)
    {      
          size_t         i;
          char* pc1= (char*)p1;
          char* pc2= (char*)p2;
          char  ch;
    
          for (i= 0; i

    And you call it like this:

    int main() {
         int i1,i2;
         double d1,d2;
         i1= 10; i2= 20;
         d1= 1.12; d2= 2.23;
         memswap_arr(&i1,&i2,sizeof(int));     //I use memswap_arr to swap two integers
         printf("i1==%d i2==%d \n",i1,i2);     //I use the SAME function to swap two doubles
         memswap_arr(&d1,&d2,sizeof(double));      
         printf("d1==%f d2==%f \n",d1,d2);
         return 0;
    }
    

    I think that this should give you an idea of how to use one function for different data types.

提交回复
热议问题