Swapping objects using pointers

后端 未结 10 1355
轻奢々
轻奢々 2020-12-03 18:20

I\'m trying to swap objects for a homework problem that uses void pointers to swap objects. The declaration of my function has to be:

void swap(void *a, voi         


        
10条回答
  •  旧时难觅i
    2020-12-03 18:47

    I had a question similar to this for my C course. I think memcopy is probably best but you can also try this:

        typedef unsigned char * ucp;
    
        void swap(void *a, void *b, int size){
          ucp c=(ucp)a;
          ucp d=(ucp)b;
          for(int i=0; i

    Basically what this does is cast both pointers to an unsigned char pointer type. Then you increment the pointer, which in the case of an unsigned char, increments one BYTE at a time. Then what you're doing is basically copying the contents of each byte at a time in memory. If anyone wants to correct or clarify on this I would appreciate it too.

提交回复
热议问题