c - copy one string in to other using pointer produce Garbage values why? -
if take array fine used *str1 , str2 not work
#include <stdio.h> void copystr(char* ,char*); int main() { char *str1="xxx"; char *str2= "yyy"; copystr(str1, str2); printf("\n %s",str2); } void copystr(char *dest,char *src) { while(*src!='\0') *dest++=*src++; *dest='\0'; return; }
char *str = "some string"
here str pointer pointing constant memory, can't edited , leads undefined behaviour.
but if declare like
char str2[] = "some string"
now str2 above pointing memory not constant , can changed. work.
more explanation here: char *array , char array[]