I have written a function to implement memcpy
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
char *memcpy(char *dest,char *src,int n){
char *ch=dest;
while (n--)
*ch++=*src++;
return dest;
}
int main(){
char *src="georgia";
int n=strlen(src);
char *dest=new char[n];
std::cout<<*memcpy(dest,src,n)<<std::endl;
return 0;
}
But it only prints a single g. Why?
Because you’re printing a single character.
This dereferences the destination buffer (
*memcpy) and therefore returns the first character of the string (which isg). You should be fine using this:Other than that, it’s still not gonna work: you need to include the terminating NULL character of your string in the copy, but
strlenexcludes it from the length of the string; so your buffer is missing 1 character. You need to add 1 tonto balance it, and everything should be fine.