-1

I am writing a small implementation of memcpy as follows.

#include "stdio.h"
int main( )
{
    int i=5;
    int j=4;
    printf("i=%d\t",i);
    swap(&i,&j,sizeof(int));
    printf("i=%d",i);
    return 0;
}


int swap(void *vp1,void *vp2,int size)
{
    char *a=(char *)vp1;
    char *b=(char *)vp2;

    for(int i=0;i<size;i++)
    {
        *a=*b;
        a++;
        b++;
    }

    return 0;
}

The output of this code is

i=5 i=33

rather than

i=5 i=4

Can anybody explain what is wrong with the code?

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
Vaibhav Sundriyal
  • 567
  • 5
  • 11
  • 18

1 Answers1

-3
#include "stdio.h"
int swap(void *vp1,void *vp2,int size)

{

     int i;

    char *a=(char *)vp1;
    char *b=(char *)vp2;

    for(i = 0; i<size;i++)
    {
     *a = *b;
     a++;
     b++;
     }
    return 0;
}

int main( )

{

    int i=5;
    int j=4;
    printf("i=%d\t",i);
    swap(&i,&j,sizeof(int));
    printf("i=%d",i);
    return 0;
}
Bo Persson
  • 90,663
  • 31
  • 146
  • 203