0

if take array it will be fine but as i used *str1 and str2 it does 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; 
 } 
Valentin Lorentz
  • 9,556
  • 6
  • 47
  • 69
chirag
  • 1
  • 1

2 Answers2

1
char *str = "some string"

Here str is a pointer pointing to a constant memory, which can't be edited and leads to undefined behaviour.

But If you declare like

char str2[] = "some string"

Now str2 above is pointing to a memory which is not constant and can be changed. Thus will work.

More explanation here: char *array and char array[]

Community
  • 1
  • 1
mSatyam
  • 531
  • 7
  • 25
0

Destination string str1 is a string literal. String literals are non modifiable. Any attempt to modify it will invoke undefined behavior.

haccks
  • 104,019
  • 25
  • 176
  • 264