chirag
chirag

Reputation: 1

copy one string in to other using pointer produce Garbage values why?

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; 
 } 

Upvotes: 0

Views: 43

Answers (2)

mSatyam
mSatyam

Reputation: 541

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[]

Upvotes: 1

haccks
haccks

Reputation: 106112

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

Upvotes: 0

Related Questions