#include<stdio.h>
#include<malloc.h>
void my_strcpy(char *sour,char *dest){
if(sour == NULL || dest == NULL){
return;
}
while(*sour != '\0'){
*dest++ = *sour++;
}
*dest = '\0';
}
int main(){
char *d = NULL;
char *s = "Angus Declan R";
d = malloc(sizeof(char*));
my_strcpy(s,d);
printf("\n %s \n",d);
return 0;
}
This func works fine and prints the string. My doubt is as the pointer "dest" will be pointing to the '\0' how does it prints the whole string(as it didnt point to the initial address of the string).
(sour == NULL || dest == NULL)(OR, rather than AND). Also, the malloc line should bed = malloc(strlen(s)+1);(dneeds to point to a buffer that is large enough to hold every character in stringsplus the NULL character)d = malloc(sizeof(char*));doesn't allocate enough memory on most systems. Usually a pointer is four or eight bytes large.